foxguard 0.12.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
use crate::engine::parser::parse_file;
use crate::rules::common::get_source_line;
use crate::rules::Rule;
use crate::{Finding, Language, Severity};
use globset::{Glob, GlobSet, GlobSetBuilder};
use regex::Regex;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::path::Path;
use std::sync::OnceLock;

const RESERVED_RULE_ID_NAMESPACES: &[&str] = &[
    "py", "js", "go", "java", "php", "ruby", "cs", "csharp", "swift", "kotlin", "rs", "rust",
    "config", "manifest",
];

/// A compiled regex that prefers the fast `regex` crate but transparently falls
/// back to `fancy-regex` (a backtracking engine) for patterns the `regex` crate
/// cannot compile — most importantly PCRE features such as lookahead
/// `(?=...)` / `(?!...)`, lookbehind `(?<=...)` / `(?<!...)`, and named
/// backreferences, which many Semgrep registry rules rely on.
///
/// The `regex` crate remains the primary path: `fancy-regex` is only used when
/// the `regex` crate rejects the pattern, so the common case keeps the linear,
/// allocation-free matching of the fast engine.
#[derive(Debug, Clone)]
pub enum CompiledRegex {
    /// Compiled with the fast, linear-time `regex` crate (the common case).
    Fast(Regex),
    /// Compiled with the backtracking `fancy-regex` engine (lookaround /
    /// backreferences). `fancy_regex::Regex::is_match` returns a `Result`; any
    /// error (e.g. backtrack-limit exceeded) is treated as "no match" rather
    /// than panicking.
    Fancy(fancy_regex::Regex),
}

impl CompiledRegex {
    /// Returns the original (normalised) regex source string of whichever
    /// backend compiled it. Used for stable fingerprinting/dedup of compiled
    /// matchers that embed a regex.
    pub fn as_str(&self) -> &str {
        match self {
            CompiledRegex::Fast(re) => re.as_str(),
            CompiledRegex::Fancy(re) => re.as_str(),
        }
    }

    /// Returns `true` if the pattern matches anywhere in `text`.
    ///
    /// For the fancy-regex backend, a matcher error (such as exceeding the
    /// backtrack limit) is treated as no-match.
    pub fn is_match(&self, text: &str) -> bool {
        match self {
            CompiledRegex::Fast(re) => re.is_match(text),
            CompiledRegex::Fancy(re) => re.is_match(text).unwrap_or(false),
        }
    }

    /// Returns the non-overlapping byte ranges `(start, end)` of every match in
    /// `text`, left-to-right — the same iteration order as
    /// [`regex::Regex::find_iter`].
    ///
    /// For the fancy-regex backend, iteration stops at the first matcher error
    /// (errors are treated as "no further matches" rather than panicking).
    pub fn find_matches(&self, text: &str) -> Vec<(usize, usize)> {
        match self {
            CompiledRegex::Fast(re) => re.find_iter(text).map(|m| (m.start(), m.end())).collect(),
            CompiledRegex::Fancy(re) => re
                .find_iter(text)
                .map_while(Result::ok)
                .map(|m| (m.start(), m.end()))
                .collect(),
        }
    }
}

// ─── YAML Schema ────────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct SemgrepFile {
    pub rules: Vec<SemgrepRuleYaml>,
}

/// Value that can be either a plain string pattern or a complex block
/// (e.g. `pattern-not-inside:` with a nested `patterns:` sub-block).
///
/// The string form is used directly as a pattern.  The block form is
/// deserialized into a raw YAML `Value` and then examined for an inner
/// `pattern:` string to extract; if none is found the constraint is
/// warn-skipped (graceful degradation consistent with the rest of the loader).
///
/// This supports rules like `last-user-is-root` in the Dockerfile registry
/// which use:
/// ```yaml
/// pattern-not-inside:
///   patterns:
///     - pattern: |
///         USER root
///         ...
///         USER $X
///     - metavariable-pattern:
///         metavariable: $X
///         patterns:
///         - pattern-not: root
/// ```
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum PatternOrBlock {
    /// Plain string — the common `pattern-not-inside: "..."` form.
    Literal(String),
    /// Complex block — accept any map/sequence so the YAML deserializes
    /// without error; we extract a usable `pattern:` string from it, if any.
    Block(serde_yaml_ng::Value),
}

impl PatternOrBlock {
    /// Extract a usable pattern string from this value.
    ///
    /// - `Literal(s)` → `Some(s)`
    /// - `Block(v)` → looks for the first `pattern:` string nested under a
    ///   `patterns:` list; returns `None` (with a warning) if nothing usable
    ///   is found.  The returned string is the first concrete sub-pattern that
    ///   can be compiled; more complex constraints (metavariable-pattern etc.)
    ///   in the block are gracefully dropped.
    pub fn into_pattern_string(self) -> Option<String> {
        match self {
            PatternOrBlock::Literal(s) => Some(s),
            PatternOrBlock::Block(v) => {
                // Try to extract the first `pattern:` string from a
                // `patterns: [{ pattern: "..." }, ...]` block.
                if let Some(clauses) = v
                    .get("patterns")
                    .and_then(serde_yaml_ng::Value::as_sequence)
                {
                    for clause in clauses {
                        if let Some(pat) =
                            clause.get("pattern").and_then(serde_yaml_ng::Value::as_str)
                        {
                            return Some(pat.to_string());
                        }
                    }
                }
                eprintln!(
                    "Warning: pattern-not-inside block has no extractable `pattern:` string; \
                     skipping constraint"
                );
                None
            }
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct SemgrepRuleYaml {
    pub id: String,
    #[serde(default)]
    pub pattern: Option<String>,
    #[serde(default, rename = "pattern-regex")]
    pub pattern_regex: Option<String>,
    #[serde(default, rename = "pattern-either")]
    pub pattern_either: Option<Vec<PatternEntry>>,
    #[serde(default, rename = "pattern-not")]
    pub pattern_not: Option<String>,
    #[serde(default, rename = "pattern-not-regex")]
    pub pattern_not_regex: Option<String>,
    #[serde(default, rename = "pattern-inside")]
    pub pattern_inside: Option<String>,
    /// `pattern-not-inside:` accepts either a plain string or a complex block
    /// (e.g. `patterns: [...]` sub-block).  See [`PatternOrBlock`].
    #[serde(default, rename = "pattern-not-inside")]
    pub pattern_not_inside: Option<PatternOrBlock>,
    #[serde(default)]
    pub patterns: Option<Vec<PatternClause>>,
    pub message: String,
    pub severity: SemgrepSeverity,
    pub languages: Vec<String>,
    #[serde(default)]
    pub metadata: Option<SemgrepMetadata>,
    #[serde(default)]
    pub paths: Option<SemgrepPaths>,
    /// Optional autofix template (Semgrep `fix:` key).  Metavariables in the
    /// template (e.g. `$X`) are substituted with bound values when a finding is
    /// built.  `fix-regex:` is not supported and is ignored.
    #[serde(default)]
    pub fix: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct PatternEntry {
    #[serde(default)]
    pub pattern: Option<String>,
    #[serde(default, rename = "pattern-regex")]
    pub pattern_regex: Option<String>,
    /// A nested `patterns:` AND-block arm, kept as a raw YAML value. Used by
    /// generic-mode package-manager rules whose `pattern-either` arms are full
    /// AND-blocks (each with a named-capture `pattern-regex` plus
    /// `metavariable-*` constraints). The AST bridge ignores this field; only
    /// the generic-mode loader consumes it (decoding leniently, so AST-only
    /// nested shapes — e.g. a `pattern-not:` whose value is itself a block —
    /// never break deserialization of an unrelated rule).
    #[serde(default)]
    pub patterns: Option<serde_yaml_ng::Value>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct PatternClause {
    #[serde(default)]
    pub pattern: Option<String>,
    #[serde(default, rename = "pattern-regex")]
    pub pattern_regex: Option<String>,
    #[serde(default, rename = "pattern-not")]
    pub pattern_not: Option<String>,
    #[serde(default, rename = "pattern-not-regex")]
    pub pattern_not_regex: Option<String>,
    #[serde(default, rename = "pattern-inside")]
    pub pattern_inside: Option<String>,
    /// `pattern-not-inside:` inside a `patterns:` block can be either a plain
    /// string or a nested block (`patterns: [...]`).  See [`PatternOrBlock`].
    #[serde(default, rename = "pattern-not-inside")]
    pub pattern_not_inside: Option<PatternOrBlock>,
    #[serde(default, rename = "pattern-either")]
    pub pattern_either: Option<Vec<PatternEntry>>,
    #[serde(default, rename = "metavariable-regex")]
    pub metavariable_regex: Option<SemgrepMetavariableRegexClause>,
    #[serde(default, rename = "metavariable-comparison")]
    pub metavariable_comparison: Option<SemgrepMetavariableComparisonClause>,
    #[serde(default, rename = "metavariable-pattern")]
    pub metavariable_pattern: Option<SemgrepMetavariablePatternClause>,
    #[serde(default, rename = "metavariable-analysis")]
    pub metavariable_analysis: Option<SemgrepMetavariableAnalysisClause>,
    /// `focus-metavariable:` — report the range of the named metavariable(s)
    /// instead of the full enclosing match.
    #[serde(default, rename = "focus-metavariable")]
    pub focus_metavariable: Option<FocusMetavariableValue>,
    /// `metavariable-type:` — constrain a metavariable to a declared type.
    #[serde(default, rename = "metavariable-type")]
    pub metavariable_type: Option<SemgrepMetavariableTypeClause>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum SemgrepSeverity {
    Error,
    Warning,
    /// `MEDIUM` is a Semgrep severity variant used by some registry rules (e.g.
    /// supply-chain / package-manager packs).  Foxguard maps it to `High`,
    /// matching the spirit of "medium" risk in the broader threat model.
    Medium,
    Info,
}

#[derive(Debug, Deserialize)]
pub struct SemgrepMetadata {
    pub cwe: Option<CweValue>,
}

#[derive(Debug, Deserialize, Default)]
pub struct SemgrepPaths {
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct SemgrepMetavariableRegexClause {
    pub metavariable: String,
    pub regex: String,
}

#[derive(Debug, Deserialize, Clone)]
pub struct SemgrepMetavariableComparisonClause {
    /// The metavariable to compare.  Some advanced Semgrep rules omit this key
    /// (they use `comparison: str($F1) == str($F2)` with both operands being
    /// metavariables inside the expression string). We make the field optional
    /// so those rules still deserialize; `from_yaml` will warn-skip the
    /// constraint when the field is absent because the comparison is outside
    /// our supported `$VAR <op> <number>` subset regardless.
    #[serde(default)]
    pub metavariable: Option<String>,
    pub comparison: String,
    /// Optional integer base for parsing (e.g. 16 for hex). Warn-skipped if
    /// present — we only support base-10 by default.
    #[serde(default)]
    pub base: Option<u32>,
    /// Optional strip flag (Semgrep strips L/U suffixes from integer literals).
    /// Warn-skipped if true — the common C-integer suffix case is handled via
    /// our own stripping logic.
    #[serde(default)]
    pub strip: Option<bool>,
}

/// Nested pattern forms supported inside `metavariable-pattern:`.
///
/// Supported: `pattern:`, `pattern-regex:`, and `pattern-either:` (of those
/// same forms). Anything else (nested `patterns:`, `metavariable-pattern:`,
/// `language:` override, etc.) is warn-skipped at build time.
/// Accepts either a single metavariable name (`"$X"`) or a list (`["$X", "$Y"]`),
/// matching the Semgrep `focus-metavariable:` YAML schema.
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub enum FocusMetavariableValue {
    Single(String),
    List(Vec<String>),
}

impl FocusMetavariableValue {
    /// Expand to a flat `Vec<String>` for uniform processing.
    pub fn into_vec(self) -> Vec<String> {
        match self {
            FocusMetavariableValue::Single(s) => vec![s],
            FocusMetavariableValue::List(v) => v,
        }
    }
}

#[derive(Debug, Deserialize, Clone)]
pub struct SemgrepMetavariablePatternClause {
    pub metavariable: String,
    #[serde(default)]
    pub pattern: Option<String>,
    #[serde(default, rename = "pattern-regex")]
    pub pattern_regex: Option<String>,
    #[serde(default, rename = "pattern-either")]
    pub pattern_either: Option<Vec<PatternEntry>>,
}

/// A `metavariable-analysis:` clause inside a `patterns:` block.
///
/// Supported analyzers:
/// - `entropy` — matches when the metavariable's bound text has high Shannon
///   entropy (≥ `ENTROPY_THRESHOLD` bits/char). Designed to flag random secrets
///   and tokens.
/// - `redos` — **warn-skipped**: a sound, cheap heuristic is not implemented;
///   the constraint is dropped and sibling clauses are unaffected.
/// - Any other analyzer → warn-skipped (graceful degradation).
#[derive(Debug, Deserialize, Clone)]
pub struct SemgrepMetavariableAnalysisClause {
    pub metavariable: String,
    pub analyzer: String,
}

/// A `metavariable-type:` clause inside a `patterns:` block.
///
/// Constrains a metavariable to a **declared** type, e.g. only match `$X` when
/// `$X` is (declared as) a `Statement`. This is the type-constraint sibling of
/// `metavariable-regex` (constrain by regex on the bound text).
#[derive(Debug, Deserialize, Clone)]
pub struct SemgrepMetavariableTypeClause {
    pub metavariable: String,
    #[serde(rename = "type")]
    pub type_name: String,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum CweValue {
    Single(String),
    List(Vec<String>),
}

// ─── Compiled Rule ──────────────────────────────────────────────────────────

/// A compiled Semgrep-compatible rule that implements the foxguard Rule trait.
pub struct SemgrepRule {
    pub id: String,
    pub message: String,
    pub severity: Severity,
    pub lang: Language,
    pub cwe: Option<String>,
    pub matcher: PatternMatcher,
    pub path_filter: Option<PathFilter>,
    /// Optional autofix template derived from the rule's `fix:` key.
    /// Metavariables (`$NAME`) are substituted with bound text when a finding
    /// is emitted; unbound tokens are left as-is.
    pub fix_template: Option<String>,
}

/// Represents the matching strategy for a rule.
// The `Combined` variant is inherently large (it holds several constraint Vecs);
// boxing the whole enum would require pervasive indirection. Suppress the lint
// here — the enum is only heap-allocated as part of a `SemgrepRule` or another
// `PatternMatcher` arm, so no stack-smashing risk.
#[derive(Debug, Clone)]
pub enum PatternMatcher {
    /// Single pattern
    Single(CompiledAstPattern),
    /// Regex match against source text
    Regex(CompiledRegex),
    /// Match any of these patterns (OR)
    Either(Vec<PatternMatcher>),
    /// Combine multiple clauses (AND): positives must all match, negatives must not
    Combined {
        positives: Vec<PatternMatcher>,
        negatives: Vec<NegativeMatcher>,
        inside: Option<CompiledAstPattern>,
        not_inside: Option<CompiledAstPattern>,
        metavariable_regexes: Vec<MetavariableRegexConstraint>,
        metavariable_comparisons: Vec<MetavariableComparisonConstraint>,
        metavariable_patterns: Vec<MetavariablePatternConstraint>,
        metavariable_analyses: Vec<MetavariableAnalysisConstraint>,
        metavariable_types: Vec<MetavariableTypeConstraint>,
        /// `focus-metavariable:` — when non-empty, the reported finding range is
        /// overridden to point at the first listed metavariable's binding range
        /// (falling back to the full match range if the metavar isn't bound).
        focus_metavariables: Vec<String>,
    },
}

#[derive(Debug, Clone)]
pub enum NegativeMatcher {
    Pattern(CompiledAstPattern),
    Regex(CompiledRegex),
}

#[derive(Clone)]
pub struct CompiledAstPattern {
    source: String,
    tree: Option<tree_sitter::Tree>,
    selector_kind: Option<String>,
}

impl fmt::Debug for CompiledAstPattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompiledAstPattern")
            .field("source", &self.source)
            .field("compiled", &self.tree.is_some())
            .field("selector_kind", &self.selector_kind)
            .finish()
    }
}

impl CompiledAstPattern {
    /// Compile a Semgrep pattern string for use as a negative (exclusion)
    /// matcher — the `pattern-not` constraint inside a taint `patterns:`
    /// AND-block. Returns `None` when the pattern does not parse into a
    /// usable tree-sitter pattern node, so callers can warn and skip
    /// instead of silently storing an unmatchable pattern.
    ///
    /// This reuses the same compilation path as SEARCH-mode `pattern-not`
    /// (see `build_matcher`), so positive and negative patterns agree on
    /// grammar handling, metavariable rewriting, and ellipsis behaviour.
    pub(crate) fn try_new(pattern: &str, lang: Language) -> Option<Self> {
        let compiled = Self::new(pattern.to_string(), lang);
        if compiled.pattern_node().is_some() {
            Some(compiled)
        } else {
            None
        }
    }

    /// Run this pattern against every node in `root` and return `true` if
    /// any match's byte range overlaps the half-open `[start_byte, end_byte)`
    /// span — i.e. the pattern matches *at* the candidate location.
    ///
    /// Used by the taint bridge's post-filter to enforce `pattern-not`
    /// against a finding's sink node: if a negative pattern matches the
    /// sink's range, the finding is suppressed. The overlap test mirrors
    /// SEARCH mode's `ranges_overlap` semantics (`build_matcher`), keeping
    /// positive/negative intersection behaviour consistent across modes.
    pub(crate) fn overlaps_range(
        &self,
        root: tree_sitter::Node<'_>,
        source: &str,
        start_byte: usize,
        end_byte: usize,
    ) -> bool {
        match_single_pattern(self, root, source)
            .iter()
            .any(|m| m.start_byte < end_byte && start_byte < m.end_byte)
    }

    /// Run this pattern against every node in `root` and return `true` if
    /// any match's byte range *contains* the half-open `[start_byte, end_byte)`
    /// span — i.e. the candidate location is textually **inside** a region
    /// this pattern matches.
    ///
    /// Used by the taint bridge's post-filter to enforce `pattern-inside`
    /// against a finding's sink node: a finding is kept only when its sink's
    /// range is contained by some region matched by a positive `pattern-inside`
    /// constraint. The containment test mirrors SEARCH mode's `pattern-inside`
    /// filtering (`build_matcher`: `r.start_byte >= start && r.end_byte <= end`),
    /// keeping inside-containment behaviour consistent across modes.
    pub(crate) fn contains_range(
        &self,
        root: tree_sitter::Node<'_>,
        source: &str,
        start_byte: usize,
        end_byte: usize,
    ) -> bool {
        match_single_pattern(self, root, source)
            .iter()
            .any(|m| m.start_byte <= start_byte && end_byte <= m.end_byte)
    }
}

#[derive(Debug, Clone)]
pub struct PathFilter {
    include: Option<GlobSet>,
    exclude: Option<GlobSet>,
}

#[derive(Debug, Clone)]
pub struct MetavariableRegexConstraint {
    metavariable: String,
    regex: CompiledRegex,
}

/// Comparison operator for `metavariable-comparison`.
#[derive(Debug, Clone, PartialEq)]
enum CmpOp {
    Lt,
    Le,
    Gt,
    Ge,
    Eq,
    Ne,
}

/// A compiled `metavariable-comparison` constraint.
/// Supports: `$VAR <op> <number>` and `<number> <op> $VAR`,
/// where `<number>` is an integer or float literal and `<op>` is one of
/// `<`, `<=`, `>`, `>=`, `==`, `!=`.
#[derive(Debug, Clone)]
pub struct MetavariableComparisonConstraint {
    metavariable: String,
    op: CmpOp,
    /// The literal value from the comparison string.
    literal: f64,
    /// If true, the expression is `literal <op> metavar` (operands flipped).
    literal_is_lhs: bool,
}

/// A compiled `metavariable-pattern:` constraint.
///
/// The binding text for `metavariable` is re-parsed as a snippet and matched
/// against `sub_matcher`. Supported sub-matcher forms: `Single` (pattern),
/// `Regex` (pattern-regex), and `Either` (pattern-either of those). Any
/// unsupported nested shape is warn-skipped at build time.
#[derive(Debug, Clone)]
pub struct MetavariablePatternConstraint {
    metavariable: String,
    sub_matcher: PatternMatcher,
    lang: Language,
}

/// Shannon entropy threshold (bits per character) above which a string is
/// considered high-entropy.
///
/// Rationale: real secrets (AWS key `AKIA…`, base64 bearer tokens, hex API
/// keys) cluster between 3.5–4.5 bits/char, while English words and common
/// identifiers sit below 3.0 bits/char.  Semgrep's built-in entropy analyzer
/// uses a learned Gaussian-mixture cutoff that is not publicly documented;
/// **3.5 bits/char** is a documented approximation that:
///
/// - flags `"Zq7Z9kW3pL8xT2nR4dB6m"` (random high-entropy token, entropy ≈ 4.0)
/// - flags a 32-char base64 token (entropy ≈ 4.75)
/// - passes `"hello"` (entropy ≈ 2.32)
/// - passes `"password"` (entropy ≈ 2.75)
///
/// The threshold is intentionally a named constant so it can be adjusted in
/// one place without a search-and-replace.
const ENTROPY_THRESHOLD: f64 = 3.5;

/// Compute Shannon entropy (bits per character) of `s`.
///
/// Returns 0.0 for an empty string.
fn shannon_entropy(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let len = s.len() as f64;
    let mut counts = [0u32; 256];
    for b in s.bytes() {
        counts[b as usize] += 1;
    }
    counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = c as f64 / len;
            -p * p.log2()
        })
        .sum()
}

/// A compiled `metavariable-analysis:` constraint.
///
/// Only `analyzer: entropy` is implemented. Other analyzers (including
/// `redos`) are warn-skipped at build time and the constraint is dropped;
/// sibling clauses are unaffected.
#[derive(Debug, Clone)]
pub struct MetavariableAnalysisConstraint {
    metavariable: String,
}

impl MetavariableAnalysisConstraint {
    /// Build from a YAML clause.  Returns `Ok(Some(_))` for `entropy`,
    /// `Ok(None)` (after printing a warning) for `redos` and unknown
    /// analyzers.
    fn from_yaml(clause: &SemgrepMetavariableAnalysisClause) -> Option<Self> {
        match clause.analyzer.as_str() {
            "entropy" => Some(Self {
                metavariable: clause.metavariable.clone(),
            }),
            "redos" => {
                eprintln!(
                    "Warning: metavariable-analysis analyzer 'redos' for {} is not \
                    implemented (no sound cheap heuristic); skipping constraint",
                    clause.metavariable
                );
                None
            }
            other => {
                eprintln!(
                    "Warning: metavariable-analysis analyzer '{}' for {} is unknown; \
                    skipping constraint",
                    other, clause.metavariable
                );
                None
            }
        }
    }

    /// Returns `true` when the bound text has Shannon entropy ≥
    /// [`ENTROPY_THRESHOLD`] bits/char.  Unbound metavariables → `false`.
    fn matches(&self, bindings: &HashMap<String, String>) -> bool {
        let Some(text) = bindings.get(&self.metavariable) else {
            return false;
        };
        shannon_entropy(text) >= ENTROPY_THRESHOLD
    }
}

/// A compiled `metavariable-type:` constraint.
///
/// Constrains the bound metavariable to a declared type. Enforcement is purely
/// **syntactic**: the metavariable must bind to a simple identifier whose
/// declaration (a parameter or a local/field with a written-out type) is
/// resolvable in the surrounding tree-sitter tree of a statically-typed
/// language. When the type cannot be resolved (the binding is a complex
/// expression, or the declaration/type is not syntactically present) the
/// constraint is treated as **unsatisfied** — the candidate is dropped rather
/// than matched, so an unresolvable type never causes an over-match.
///
/// Rules whose language has no syntactic type resolution here are *not loaded*
/// at all (see [`metavariable_type_enforceable`] / `build_matcher`), so a
/// dropped-because-unenforceable constraint can never silently broaden a rule.
#[derive(Debug, Clone)]
pub struct MetavariableTypeConstraint {
    metavariable: String,
    /// The required type, normalized to its simple name (see
    /// [`normalize_type_name`]).
    type_name: String,
    lang: Language,
}

impl MetavariableTypeConstraint {
    /// Build a constraint for an enforceable language. Callers must gate on
    /// [`metavariable_type_enforceable`] first; this only normalizes the type.
    fn from_yaml(clause: &SemgrepMetavariableTypeClause, lang: Language) -> Self {
        Self {
            metavariable: clause.metavariable.clone(),
            type_name: normalize_type_name(&clause.type_name),
            lang,
        }
    }

    /// `true` when the metavariable is bound to a simple identifier whose
    /// resolved declared type (simple name) equals the required type. Any
    /// failure to resolve → `false` (drop the candidate; never over-match).
    fn matches(
        &self,
        root: tree_sitter::Node,
        source: &str,
        bindings: &HashMap<String, String>,
        binding_ranges: &HashMap<String, MetavarRange>,
    ) -> bool {
        let Some(text) = bindings.get(&self.metavariable) else {
            return false;
        };
        let name = text.trim();
        if !is_simple_identifier(name) {
            return false;
        }
        let Some(&(line, col, _, _)) = binding_ranges.get(&self.metavariable) else {
            return false;
        };
        let Some(offset) = position_to_byte_offset(source, line, col) else {
            return false;
        };
        match resolve_declared_type(self.lang, root, source, name, offset) {
            Some(declared) => normalize_type_name(&declared) == self.type_name,
            None => false,
        }
    }
}

/// Whether `metavariable-type:` can be **enforced** for `lang`. Only
/// statically-typed languages whose declarations carry a syntactic type that
/// [`resolve_declared_type`] knows how to read qualify. Rules that use
/// `metavariable-type:` on any other language are skipped by the loader rather
/// than loaded with the constraint dropped (which would over-match).
fn metavariable_type_enforceable(lang: Language) -> bool {
    matches!(
        lang,
        Language::Java
            | Language::CSharp
            | Language::Go
            | Language::Kotlin
            // TypeScript is parsed under `Language::JavaScript` (grammar chosen
            // by file extension). Plain JS has no type annotations, in which
            // case resolution fails and candidates are dropped (safe under-match).
            | Language::JavaScript
    )
}

/// Normalize a declared/required type to its simple name for comparison:
/// strip a leading `:` (TypeScript `type_annotation` text), generic arguments
/// (`List<String>` → `List`), array suffixes (`String[]` → `String`) and any
/// package/namespace qualifier (`java.sql.Statement` → `Statement`).
fn normalize_type_name(raw: &str) -> String {
    let mut s = raw.trim();
    // TypeScript `type_annotation` nodes include the leading colon.
    s = s.trim_start_matches(':').trim();
    // Drop generic type arguments.
    if let Some(idx) = s.find('<') {
        s = s[..idx].trim_end();
    }
    // Drop array/index suffixes.
    if let Some(idx) = s.find('[') {
        s = s[..idx].trim_end();
    }
    // Keep only the final path segment of a qualified name.
    if let Some(idx) = s.rfind(['.', ':']) {
        s = &s[idx + 1..];
    }
    s.trim().to_string()
}

/// A bound metavariable is type-resolvable only when it binds to a plain
/// identifier (not a field access, call, literal, or other expression).
fn is_simple_identifier(text: &str) -> bool {
    let mut chars = text.chars();
    match chars.next() {
        Some(c) if c.is_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_alphanumeric() || c == '_')
}

// ─── Comparison parser ───────────────────────────────────────────────────────

/// Parse a comparison string of the form `$VAR <op> <number>` or
/// `<number> <op> $VAR`.  Returns `Err` with a human-readable message for
/// anything outside that supported subset (caller will warn-skip it).
fn parse_comparison(comparison: &str) -> Result<(String, CmpOp, f64, bool), String> {
    let s = comparison.trim();

    // Try longest operator first to avoid e.g. `<` matching `<=`.
    const OPS: &[(&str, CmpOp)] = &[
        ("<=", CmpOp::Le),
        (">=", CmpOp::Ge),
        ("!=", CmpOp::Ne),
        ("==", CmpOp::Eq),
        ("<", CmpOp::Lt),
        (">", CmpOp::Gt),
    ];

    for (op_str, op) in OPS {
        if let Some(idx) = s.find(op_str) {
            let lhs = s[..idx].trim();
            let rhs = s[idx + op_str.len()..].trim();

            // Figure out which side is the metavar and which is the literal.
            let (metavar, literal_str, literal_is_lhs) = if lhs.starts_with('$') {
                (lhs, rhs, false)
            } else if rhs.starts_with('$') {
                (rhs, lhs, true)
            } else {
                return Err(format!("metavariable-comparison: no metavariable in '{s}'"));
            };

            // Validate the metavar token.
            if metavariable_key(metavar).is_none() {
                return Err(format!(
                    "metavariable-comparison: invalid metavariable token '{metavar}' in '{s}'"
                ));
            }

            // Strip common C integer suffixes (L, UL, LL, etc.) and leading
            // 0x/0b so we can parse as f64.
            let literal_str = strip_numeric_suffixes(literal_str);
            let literal: f64 = parse_numeric(&literal_str).ok_or_else(|| {
                format!(
                    "metavariable-comparison: cannot parse numeric literal '{literal_str}' in '{s}'"
                )
            })?;

            return Ok((metavar.to_string(), op.clone(), literal, literal_is_lhs));
        }
    }

    Err(format!(
        "metavariable-comparison: unsupported comparison expression '{s}'"
    ))
}

/// Strip trailing C-style suffixes (`L`, `U`, `UL`, `LL`, `ULL`, etc.)
/// from an integer-literal string (case-insensitive), so `10L` parses as `10`.
fn strip_numeric_suffixes(s: &str) -> String {
    let upper = s.to_uppercase();
    // Hex/binary literals end in digits that can look like suffixes (e.g. the
    // trailing `F` in `0xFF`), so never strip from them.
    if upper.starts_with("0X") || upper.starts_with("0B") {
        return upper;
    }
    // Strip C-style integer/float suffixes: L/U (int) and F (float, e.g. `3.14f`).
    upper.trim_end_matches(['L', 'U', 'F']).to_string()
}

/// Parse a numeric string (decimal int, hex `0x…`, binary `0b…`, or float)
/// into an `f64`.
fn parse_numeric(s: &str) -> Option<f64> {
    let s = s.trim();
    if s.is_empty() {
        return None;
    }

    // Hex integer
    if let Some(hex) = s.strip_prefix("0X").or_else(|| s.strip_prefix("0x")) {
        return i64::from_str_radix(hex, 16).ok().map(|v| v as f64);
    }

    // Binary integer
    if let Some(bin) = s.strip_prefix("0B").or_else(|| s.strip_prefix("0b")) {
        return i64::from_str_radix(bin, 2).ok().map(|v| v as f64);
    }

    // Float or decimal integer — let Rust's built-in parser handle it.
    s.parse::<f64>().ok()
}

impl Rule for SemgrepRule {
    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 applies_to_path(&self, path: &Path) -> bool {
        self.path_filter
            .as_ref()
            .is_none_or(|filter| filter.matches(path))
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let root = tree.root_node();

        // Collect all matching nodes
        let matches = match_pattern_in_tree(&self.matcher, root, source);

        for matched_node_range in matches {
            let fix_suggestion = self
                .fix_template
                .as_deref()
                .map(|tmpl| apply_fix_template(tmpl, &matched_node_range.bindings));
            findings.push(Finding {
                rule_id: self.id.clone(),
                severity: self.severity,
                cwe: self.cwe.clone(),
                description: self.message.clone(),
                file: String::new(),
                line: matched_node_range.line,
                column: matched_node_range.column,
                end_line: matched_node_range.end_line,
                end_column: matched_node_range.end_column,
                snippet: matched_node_range.snippet,
                source_line: None,
                source_description: None,
                sink_line: None,
                sink_description: None,
                fix_suggestion,
                sink_start_byte: None,
                sink_end_byte: None,
                // External Semgrep rules are inherently fuzzier than
                // curated built-in AST-walked rules. See issue #207.
                confidence: 0.7,
                taint_hops: None,
                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![],
                crypto_material: None,
            });
        }

        findings
    }
}

impl PathFilter {
    pub(crate) fn from_yaml(paths: Option<&SemgrepPaths>) -> Result<Option<Self>, String> {
        let Some(paths) = paths else {
            return Ok(None);
        };

        let include = compile_globset(&paths.include)?;
        let exclude = compile_globset(&paths.exclude)?;

        Ok(Some(Self { include, exclude }))
    }

    pub(crate) fn matches(&self, path: &Path) -> bool {
        let normalized = normalize_rule_path(path);

        if let Some(include) = &self.include {
            if !include.is_match(&normalized) {
                return false;
            }
        }

        if let Some(exclude) = &self.exclude {
            if exclude.is_match(&normalized) {
                return false;
            }
        }

        true
    }
}

impl MetavariableRegexConstraint {
    /// Build from a YAML clause.
    ///
    /// Returns `Some(_)` on success, `None` (after printing a warning) when the
    /// regex uses features that the Rust `regex` crate does not support
    /// (lookaheads / lookbehinds / `\Z`, etc.).  The caller continues loading
    /// the rest of the rule's clauses — this mirrors the behaviour of
    /// `MetavariableAnalysisConstraint::from_yaml`.
    fn from_yaml(clause: &SemgrepMetavariableRegexClause) -> Option<Self> {
        match compile_regex(&clause.regex) {
            Ok(regex) => Some(Self {
                metavariable: clause.metavariable.clone(),
                regex,
            }),
            Err(e) => {
                eprintln!(
                    "Warning: metavariable-regex for {} uses an unsupported regex ({}); \
                     skipping constraint",
                    clause.metavariable, e
                );
                None
            }
        }
    }

    fn matches(&self, bindings: &HashMap<String, String>) -> bool {
        bindings
            .get(&self.metavariable)
            .is_some_and(|value| self.regex.is_match(value))
    }
}

impl MetavariableComparisonConstraint {
    /// Build a constraint from a parsed YAML clause.
    ///
    /// Returns `Err` (caller should warn-skip) for:
    /// - unsupported expression shapes (no metavar, non-numeric literal, etc.)
    /// - `base:` values other than 10 (warn-skip only the constraint entry)
    fn from_yaml(clause: &SemgrepMetavariableComparisonClause) -> Result<Self, String> {
        // Warn-skip non-base-10 requests — we accept base:10 or absent.
        if let Some(base) = clause.base {
            if base != 10 {
                return Err(format!(
                    "metavariable-comparison: base:{base} is not supported (only base:10); skipping constraint"
                ));
            }
        }

        // Some advanced Semgrep rules use `comparison:` without an explicit
        // `metavariable:` key (e.g. `comparison: str($F1) == str($F2)` with
        // both operands as metavar expressions). The `metavariable` field is
        // optional in the YAML schema (see `SemgrepMetavariableComparisonClause`).
        // Those rules fall outside our supported `$VAR <op> <number>` subset, so
        // we warn-skip the constraint without failing the whole rule load.
        if clause.metavariable.is_none() {
            return Err(format!(
                "metavariable-comparison: no `metavariable:` key in clause '{}'; \
                 the comparison uses an unsupported expression form — skipping constraint",
                clause.comparison
            ));
        }

        let (metavariable, op, literal, literal_is_lhs) = parse_comparison(&clause.comparison)?;

        Ok(Self {
            metavariable,
            op,
            literal,
            literal_is_lhs,
        })
    }

    /// Evaluate the comparison against the bound metavariable.
    ///
    /// Returns `false` (no match) if:
    /// - the metavariable is not bound in `bindings`
    /// - the bound text is not parseable as a number after suffix stripping
    fn matches(&self, bindings: &HashMap<String, String>) -> bool {
        let Some(value_text) = bindings.get(&self.metavariable) else {
            return false;
        };

        // Attempt to parse the bound text as a number.
        let stripped = strip_numeric_suffixes(value_text.trim());
        let Some(value) = parse_numeric(&stripped) else {
            return false;
        };

        // `literal_is_lhs` means the original expression was `literal <op> $VAR`.
        // We flip the operand order so `lhs` and `rhs` are consistent.
        let (lhs, rhs) = if self.literal_is_lhs {
            (self.literal, value)
        } else {
            (value, self.literal)
        };

        match self.op {
            CmpOp::Lt => lhs < rhs,
            CmpOp::Le => lhs <= rhs,
            CmpOp::Gt => lhs > rhs,
            CmpOp::Ge => lhs >= rhs,
            // Exact equality: both operands come from parsing the same kind of
            // numeral, so matching Semgrep's Python exact-`==` semantics (not an
            // epsilon band) is both simpler and more correct.
            CmpOp::Eq => lhs == rhs,
            CmpOp::Ne => lhs != rhs,
        }
    }
}

impl MetavariablePatternConstraint {
    /// Build a `MetavariablePatternConstraint` from a YAML clause.
    ///
    /// Returns `None` (after printing a warning) for unsupported nested shapes
    /// such as nested `patterns:`, `metavariable-pattern:`, or a `language:`
    /// override — consistent with the codebase's graceful-degradation style.
    fn from_yaml(clause: &SemgrepMetavariablePatternClause, lang: Language) -> Option<Self> {
        let sub_matcher = if let Some(ref pat) = clause.pattern {
            PatternMatcher::Single(CompiledAstPattern::new(pat.clone(), lang))
        } else if let Some(ref regex) = clause.pattern_regex {
            match compile_regex(regex) {
                Ok(r) => PatternMatcher::Regex(r),
                Err(e) => {
                    eprintln!(
                        "Warning: metavariable-pattern for {} has invalid pattern-regex: {}; skipping constraint",
                        clause.metavariable, e
                    );
                    return None;
                }
            }
        } else if let Some(ref entries) = clause.pattern_either {
            match build_either_matchers(entries, lang) {
                Ok(matchers) => PatternMatcher::Either(matchers),
                Err(e) => {
                    eprintln!(
                        "Warning: metavariable-pattern for {} has invalid pattern-either: {}; skipping constraint",
                        clause.metavariable, e
                    );
                    return None;
                }
            }
        } else {
            eprintln!(
                "Warning: metavariable-pattern for {} has no supported nested pattern form \
                (pattern, pattern-regex, or pattern-either); skipping constraint",
                clause.metavariable
            );
            return None;
        };

        Some(Self {
            metavariable: clause.metavariable.clone(),
            sub_matcher,
            lang,
        })
    }

    /// Returns `true` when the bound text for `self.metavariable` matches
    /// `self.sub_matcher`. Unparseable binding text is treated as no-match.
    fn matches(&self, bindings: &HashMap<String, String>) -> bool {
        let Some(bound_text) = bindings.get(&self.metavariable) else {
            return false;
        };

        match &self.sub_matcher {
            // For a regex sub-matcher we don't need to re-parse the binding.
            PatternMatcher::Regex(regex) => regex.is_match(bound_text),

            // For AST sub-matchers, re-parse the binding text as a snippet
            // in the rule's language.  If parsing yields no tree we treat
            // it as no-match rather than crashing.
            _ => {
                let Some(tree) = parse_file(bound_text, self.lang) else {
                    return false;
                };
                let root = tree.root_node();
                !match_pattern_in_tree(&self.sub_matcher, root, bound_text).is_empty()
            }
        }
    }
}

impl CompiledAstPattern {
    fn new(source: String, lang: Language) -> Self {
        let source = prepare_pattern_for_grammar(source, lang);
        let tree = parse_file(&source, lang);
        let selector_kind = tree
            .as_ref()
            .and_then(|tree| first_meaningful_node(tree.root_node(), &source))
            .and_then(|node| selector_kind_for_pattern(node, &source));

        Self {
            source,
            tree,
            selector_kind,
        }
    }

    fn pattern_node(&self) -> Option<tree_sitter::Node<'_>> {
        let tree = self.tree.as_ref()?;
        first_meaningful_node(tree.root_node(), &self.source)
    }
}

const GO_ELLIPSIS_PLACEHOLDER: &str = "__foxguard_semgrep_ellipsis";
const GO_METAVAR_PREFIX: &str = "__foxguard_semgrep_meta_";

/// Rewrite/wrap a Semgrep pattern in language-specific boilerplate so the
/// grammar parses it without falling back to misleading `ERROR` nodes.
///
/// Only applied when the bare pattern fails to parse cleanly: this keeps the
/// wrapping conservative and avoids surprising existing patterns that already
/// parse fine (e.g. a full Go function declaration).
fn prepare_pattern_for_grammar(source: String, lang: Language) -> String {
    match lang {
        Language::Go => {
            // If the bare pattern already parses without errors, leave it.
            if let Some(tree) = parse_file(&source, lang) {
                if !tree.root_node().has_error() {
                    return source;
                }
            }

            let source = rewrite_go_semgrep_micro_syntax(&source);
            let package_scoped = format!("package _\n{source}\n");
            if let Some(tree) = parse_file(&package_scoped, lang) {
                if !tree.root_node().has_error() {
                    return package_scoped;
                }
            }

            format!("package _\nfunc _() {{\n{source}\n}}\n")
        }
        _ => source,
    }
}

fn rewrite_go_semgrep_micro_syntax(source: &str) -> String {
    static METAVARS_RE: OnceLock<Regex> = OnceLock::new();
    let metavars = METAVARS_RE
        .get_or_init(|| Regex::new(r"\$([A-Za-z0-9_]+)").expect("valid metavariable regex"));
    let rewritten = metavars
        .replace_all(source, format!("{GO_METAVAR_PREFIX}$1"))
        .to_string()
        .replace("...", GO_ELLIPSIS_PLACEHOLDER);

    static FUNC_ELLIPSIS_RE: OnceLock<Regex> = OnceLock::new();
    let func_ellipsis_params = FUNC_ELLIPSIS_RE.get_or_init(|| {
        Regex::new(&format!(
            r"(func\s+[A-Za-z_][A-Za-z0-9_]*\s*)\(\s*{}\s*\)",
            regex::escape(GO_ELLIPSIS_PLACEHOLDER)
        ))
        .expect("valid Go func ellipsis regex")
    });

    func_ellipsis_params
        .replace_all(&rewritten, "$1()")
        .to_string()
}

// ─── Pattern Matching Engine ────────────────────────────────────────────────

/// Source span for a single metavariable binding: (line, column, end_line, end_column).
/// All values are 1-based, mirroring `MatchRange`.
type MetavarRange = (usize, usize, usize, usize);

#[derive(Debug, Clone)]
struct MatchRange {
    start_byte: usize,
    end_byte: usize,
    line: usize,
    column: usize,
    end_line: usize,
    end_column: usize,
    snippet: String,
    bindings: HashMap<String, String>,
    /// Source range for each bound metavariable: metavar name → (line, col, end_line, end_col).
    binding_ranges: HashMap<String, MetavarRange>,
}

type MatchResult = Vec<MatchRange>;

fn match_pattern_in_tree(
    matcher: &PatternMatcher,
    root: tree_sitter::Node,
    source: &str,
) -> MatchResult {
    match matcher {
        PatternMatcher::Single(pat) => match_single_pattern(pat, root, source),
        PatternMatcher::Regex(regex) => match_regex_pattern(regex, source),
        PatternMatcher::Either(matchers) => {
            let mut results = Vec::new();
            for matcher in matchers {
                results.extend(match_pattern_in_tree(matcher, root, source));
            }
            results.sort_by_key(|r| (r.start_byte, r.end_byte));
            results.dedup_by_key(|r| (r.start_byte, r.end_byte));
            results
        }
        PatternMatcher::Combined {
            positives,
            negatives,
            inside,
            not_inside,
            metavariable_regexes,
            metavariable_comparisons,
            metavariable_patterns,
            metavariable_analyses,
            metavariable_types,
            focus_metavariables,
        } => {
            // If we have an inside pattern, only search within matching contexts
            let search_roots = if let Some(inside_pat) = inside {
                let inside_matches = match_single_pattern(inside_pat, root, source);
                inside_matches
                    .iter()
                    .map(|m| (m.start_byte, m.end_byte))
                    .collect::<Vec<_>>()
            } else {
                vec![]
            };

            let excluded_roots = if let Some(not_inside_pat) = not_inside {
                let excluded_matches = match_single_pattern(not_inside_pat, root, source);
                excluded_matches
                    .iter()
                    .map(|m| (m.start_byte, m.end_byte))
                    .collect::<Vec<_>>()
            } else {
                vec![]
            };

            // Find all positive matches
            let mut candidates: Option<Vec<MatchRange>> = None;
            for pos in positives {
                let matches = match_pattern_in_tree(pos, root, source);
                candidates = Some(match candidates {
                    None => matches,
                    Some(prev) => intersect_match_sets(prev, matches),
                });
            }

            let mut results = candidates.unwrap_or_default();

            // Filter out negative matches
            for neg in negatives {
                let neg_matches = match_negative_pattern(neg, root, source);
                results.retain(|r| !neg_matches.iter().any(|n| ranges_overlap(r, n)));
            }

            // If inside constraint, filter to only matches within those ranges
            if !search_roots.is_empty() {
                results.retain(|r| {
                    search_roots
                        .iter()
                        .any(|(start, end)| r.start_byte >= *start && r.end_byte <= *end)
                });
            }

            if !excluded_roots.is_empty() {
                results.retain(|r| {
                    !excluded_roots
                        .iter()
                        .any(|(start, end)| r.start_byte >= *start && r.end_byte <= *end)
                });
            }

            for constraint in metavariable_regexes {
                results.retain(|r| constraint.matches(&r.bindings));
            }

            for constraint in metavariable_comparisons {
                results.retain(|r| constraint.matches(&r.bindings));
            }

            for constraint in metavariable_patterns {
                results.retain(|r| constraint.matches(&r.bindings));
            }

            for constraint in metavariable_analyses {
                results.retain(|r| constraint.matches(&r.bindings));
            }

            // metavariable-type: keep only candidates whose bound identifier
            // resolves to the required declared type. Unresolvable → dropped.
            for constraint in metavariable_types {
                results
                    .retain(|r| constraint.matches(root, source, &r.bindings, &r.binding_ranges));
            }

            // focus-metavariable: override each result's reported range with the
            // first listed metavariable that is bound. Fall back to the full match
            // range if none of the focus metavars are bound (do not drop the finding).
            if !focus_metavariables.is_empty() {
                for result in &mut results {
                    for fmv in focus_metavariables.iter() {
                        if let Some(&(fline, fcol, fend_line, fend_col)) =
                            result.binding_ranges.get(fmv.as_str())
                        {
                            result.line = fline;
                            result.column = fcol;
                            result.end_line = fend_line;
                            result.end_column = fend_col;
                            // Update snippet to the focused metavar's source line.
                            if let Some(bound_text) = result.bindings.get(fmv.as_str()) {
                                // We derive the byte offset from line/col for snippet lookup.
                                result.snippet = find_source_line_by_line(source, fline)
                                    .unwrap_or_else(|| bound_text.clone());
                            }
                            break;
                        }
                    }
                }
            }

            results
        }
    }
}

/// Match a single pattern string against every node in the tree.
fn match_single_pattern(
    pattern: &CompiledAstPattern,
    root: tree_sitter::Node,
    source: &str,
) -> MatchResult {
    let mut results = Vec::new();

    let Some(pat_node) = pattern.pattern_node() else {
        return results;
    };

    // Walk every node in the target tree and try matching
    walk_and_match(root, source, pat_node, pattern, &mut results);

    results
}

fn match_regex_pattern(regex: &CompiledRegex, source: &str) -> MatchResult {
    regex
        .find_matches(source)
        .into_iter()
        .map(|(start, end)| {
            let (line, column) = byte_offset_to_position(source, start);
            let (end_line, end_column) = byte_offset_to_position(source, end);
            MatchRange {
                start_byte: start,
                end_byte: end,
                line,
                column,
                end_line,
                end_column,
                snippet: get_source_line(source, start),
                bindings: HashMap::new(),
                binding_ranges: HashMap::new(),
            }
        })
        .collect()
}

/// Skip wrapper nodes (module, program, expression_statement) to get the real pattern.
fn first_meaningful_node<'a>(
    node: tree_sitter::Node<'a>,
    _source: &str,
) -> Option<tree_sitter::Node<'a>> {
    let kind = node.kind();

    // These are top-level wrappers that tree-sitter adds
    if kind == "module"
        || kind == "program"
        || kind == "source_file"
        || kind == "script"
        // tree-sitter-clojure-orchard names its top-level wrapper `source`.
        || kind == "source"
    {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            // Skip the synthetic Go prelude that `prepare_pattern_for_grammar`
            // injects (`package _`) so the meaningful pattern node is the
            // user-supplied one. See #390.
            if !child.is_extra() && child.kind() != "package_clause" {
                return first_meaningful_node(child, _source);
            }
        }
        return None;
    }

    // Unwrap the synthetic Go prelude function (`func _() { <pattern> }`)
    // generated by `prepare_pattern_for_grammar`. Identified by its `_` name,
    // so user-supplied function patterns are left alone. See #390.
    if kind == "function_declaration" {
        if let Some(name) = node.child_by_field_name("name") {
            if &_source[name.byte_range()] == "_" {
                if let Some(body) = node.child_by_field_name("body") {
                    let mut cursor = body.walk();
                    let stmts: Vec<_> = body.named_children(&mut cursor).collect();
                    // `func _() { <stmt> }` → drill into the first
                    // statement_list child, then into its first statement.
                    if let Some(first) = stmts.into_iter().next() {
                        if first.kind() == "statement_list" {
                            let mut c2 = first.walk();
                            let inner: Vec<_> = first.named_children(&mut c2).collect();
                            if let Some(stmt) = inner.into_iter().next() {
                                return first_meaningful_node(stmt, _source);
                            }
                        }
                        return first_meaningful_node(first, _source);
                    }
                }
            }
        }
    }

    // expression_statement wraps a bare expression
    if kind == "expression_statement" {
        if let Some(child) = node.child(0) {
            return Some(child);
        }
    }

    Some(node)
}

fn selector_kind_for_pattern(node: tree_sitter::Node<'_>, source: &str) -> Option<String> {
    let text = &source[node.byte_range()];
    let trimmed = text.trim();
    if metavariable_key(trimmed).is_some() || is_ellipsis_pattern(trimmed) {
        return None;
    }

    Some(node.kind().to_string())
}

fn selector_allows_node(selector_kind: Option<&str>, node: tree_sitter::Node<'_>) -> bool {
    match selector_kind {
        None => true,
        Some(kind) => {
            node.kind() == kind
                // Preserve the older wrapper-leniency path in `match_node`;
                // single-child wrappers may still match their child.
                || node.named_child_count() == 1
                || node.child_count() == 1
        }
    }
}

fn walk_and_match(
    node: tree_sitter::Node,
    source: &str,
    pat_node: tree_sitter::Node,
    pattern: &CompiledAstPattern,
    results: &mut MatchResult,
) {
    if selector_allows_node(pattern.selector_kind.as_deref(), node) {
        let mut bindings = HashMap::new();
        let mut binding_ranges: HashMap<String, MetavarRange> = HashMap::new();
        if match_node(
            node,
            source,
            pat_node,
            &pattern.source,
            &mut bindings,
            &mut binding_ranges,
        ) {
            let start = node.start_position();
            let end = node.end_position();
            results.push(MatchRange {
                start_byte: node.start_byte(),
                end_byte: node.end_byte(),
                line: start.row + 1,
                column: start.column + 1,
                end_line: end.row + 1,
                end_column: end.column + 1,
                snippet: get_source_line(source, node.start_byte()),
                bindings,
                binding_ranges,
            });
            // Don't recurse into children of a matched node to avoid duplicates
            return;
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_and_match(child, source, pat_node, pattern, results);
    }
}

/// Try to match a pattern AST node against a target AST node.
/// Returns true if they match, populating metavariable bindings and their source ranges.
fn match_node(
    target: tree_sitter::Node,
    target_src: &str,
    pattern: tree_sitter::Node,
    pat_src: &str,
    bindings: &mut HashMap<String, String>,
    binding_ranges: &mut HashMap<String, MetavarRange>,
) -> bool {
    let pat_text = &pat_src[pattern.byte_range()];

    // ── Metavariable: $X matches any node ──
    if let Some(metavar) = metavariable_key(pat_text) {
        let target_text = &target_src[target.byte_range()];
        if let Some(existing) = bindings.get(&metavar) {
            return existing == target_text;
        }
        let start = target.start_position();
        let end = target.end_position();
        bindings.insert(metavar.clone(), target_text.to_string());
        binding_ranges.insert(
            metavar,
            (start.row + 1, start.column + 1, end.row + 1, end.column + 1),
        );
        return true;
    }

    // ── Ellipsis: ... matches anything ──
    if is_ellipsis_pattern(pat_text) {
        return true;
    }

    // ── String literal "..." matches any string ──
    if is_any_string_pattern(pat_text) && is_string_node(target, target_src) {
        return true;
    }

    // ── Leaf nodes: compare text directly ──
    if pattern.child_count() == 0 {
        let target_text = &target_src[target.byte_range()];
        return pat_text == target_text;
    }

    // ── Non-leaf: kinds must match (approximately) ──
    // Be lenient: if kinds differ, we still try if the structure matches
    if pattern.kind() != target.kind() {
        // Allow some flexibility for expression wrappers
        if pattern.child_count() == 1 {
            if let Some(pc) = pattern.child(0) {
                return match_node(target, target_src, pc, pat_src, bindings, binding_ranges);
            }
        }
        if target.child_count() == 1 {
            if let Some(tc) = target.child(0) {
                return match_node(tc, target_src, pattern, pat_src, bindings, binding_ranges);
            }
        }
        return false;
    }

    if let Some(pattern_gap) = operator_token(pattern, pat_src) {
        match operator_token(target, target_src) {
            Some(target_gap) if target_gap == pattern_gap => {}
            _ => return false,
        }
    }

    // ── Match children, handling ... ellipsis ──
    let pat_children = named_children(pattern);
    let target_children = named_children(target);

    match_children_with_ellipsis(
        &target_children,
        target_src,
        &pat_children,
        pat_src,
        bindings,
        binding_ranges,
    )
}

fn named_children(node: tree_sitter::Node) -> Vec<tree_sitter::Node> {
    let mut cursor = node.walk();
    node.named_children(&mut cursor).collect()
}

fn operator_token(node: tree_sitter::Node, source: &str) -> Option<String> {
    if !matches!(
        node.kind(),
        "binary_expression" | "binary_operator" | "boolean_operator" | "comparison_operator"
    ) {
        return None;
    }

    let children = named_children(node);
    if children.len() < 2 {
        return None;
    }

    let gap = &source[children[0].end_byte()..children[1].start_byte()];
    let normalized = gap
        .chars()
        .filter(|c| !c.is_whitespace() && *c != '$')
        .collect::<String>();

    (!normalized.is_empty()).then_some(normalized)
}

/// Check if a pattern child sequence at index `pi` represents a split metavariable
/// (e.g., ERROR("$") + identifier("VAR") -> "$VAR").
fn check_split_metavar(
    pat_children: &[tree_sitter::Node],
    pi: usize,
    pat_src: &str,
) -> Option<String> {
    if pi + 1 >= pat_children.len() {
        return None;
    }
    let first = pat_children[pi];
    let second = pat_children[pi + 1];
    let first_text = &pat_src[first.byte_range()];
    let second_text = &pat_src[second.byte_range()];

    // Case 1: ERROR node with "$" followed by identifier
    if first.kind() == "ERROR" && first_text.trim() == "$" && second.kind() == "identifier" {
        let metavar = format!("${}", second_text);
        return Some(metavar);
    }

    // Case 2: ERROR node that contains the full "$VAR" text
    if first.kind() == "ERROR" {
        return metavariable_key(first_text);
    }

    None
}

/// Match pattern children against target children, handling `...` ellipsis.
fn match_children_with_ellipsis(
    target_children: &[tree_sitter::Node],
    target_src: &str,
    pat_children: &[tree_sitter::Node],
    pat_src: &str,
    bindings: &mut HashMap<String, String>,
    binding_ranges: &mut HashMap<String, MetavarRange>,
) -> bool {
    if pat_children.is_empty() {
        return true;
    }

    let mut ti = 0;
    let mut pi = 0;

    while pi < pat_children.len() {
        let pat_child = pat_children[pi];
        let pat_text = &pat_src[pat_child.byte_range()];

        if is_ellipsis_pattern(pat_text) {
            // Ellipsis: skip zero or more target children
            pi += 1;
            if pi >= pat_children.len() {
                // ... at the end matches everything remaining
                return true;
            }
            // Try to find a target child that matches the next pattern child
            let next_pat = pat_children[pi];
            while ti < target_children.len() {
                let mut sub_bindings = bindings.clone();
                let mut sub_ranges = binding_ranges.clone();
                if match_node(
                    target_children[ti],
                    target_src,
                    next_pat,
                    pat_src,
                    &mut sub_bindings,
                    &mut sub_ranges,
                ) {
                    // Continue matching from here
                    *bindings = sub_bindings;
                    *binding_ranges = sub_ranges;
                    pi += 1;
                    ti += 1;
                    break;
                }
                ti += 1;
            }
            if ti > target_children.len() {
                return false;
            }
        } else if let Some(metavar) = check_split_metavar(pat_children, pi, pat_src) {
            // Split metavar: ERROR("$") + identifier("VAR") => treat as $VAR
            if ti >= target_children.len() {
                return false;
            }
            let target_node = target_children[ti];
            let target_text = &target_src[target_node.byte_range()];
            if let Some(existing) = bindings.get(&metavar) {
                if existing != target_text {
                    return false;
                }
            } else {
                let start = target_node.start_position();
                let end = target_node.end_position();
                bindings.insert(metavar.clone(), target_text.to_string());
                binding_ranges.insert(
                    metavar.clone(),
                    (start.row + 1, start.column + 1, end.row + 1, end.column + 1),
                );
            }
            ti += 1;
            // Skip both the ERROR and identifier pattern children
            pi += 2;
        } else if pat_child.kind() == "ERROR" && pat_src[pat_child.byte_range()].trim() == "$" {
            // Lone ERROR "$" without following identifier -- skip it
            pi += 1;
        } else {
            if ti >= target_children.len() {
                return false;
            }
            if !match_node(
                target_children[ti],
                target_src,
                pat_child,
                pat_src,
                bindings,
                binding_ranges,
            ) {
                return false;
            }
            ti += 1;
            pi += 1;
        }
    }

    true
}

/// Check if text looks like a Semgrep metavariable: $VAR, $X, $DB, etc.
#[cfg(test)]
fn is_metavar(text: &str) -> bool {
    metavariable_key(text).is_some()
}

/// Substitute bound metavariable values into a Semgrep `fix:` template.
///
/// Tokens of the form `$NAME` (where `NAME` is one or more ASCII alphanumeric
/// or underscore characters) are replaced with the text bound to that
/// metavariable.  Unbound tokens are left literal.  The replacement is applied
/// longest-match-first so that e.g. `$FOOBAR` is not split into `$FOO` + `BAR`.
fn apply_fix_template(template: &str, bindings: &HashMap<String, String>) -> String {
    static METAVAR_RE: OnceLock<Regex> = OnceLock::new();
    let re = METAVAR_RE.get_or_init(|| {
        Regex::new(r"\$[A-Za-z0-9_]+").expect("valid metavariable regex for fix template")
    });
    re.replace_all(template, |caps: &regex::Captures<'_>| -> String {
        let token = caps.get(0).map_or("", |m| m.as_str());
        bindings
            .get(token)
            .cloned()
            .unwrap_or_else(|| token.to_string())
    })
    .into_owned()
}

fn metavariable_key(text: &str) -> Option<String> {
    let t = text.trim();
    if t.starts_with('$')
        && t.len() > 1
        && t[1..]
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        return Some(t.to_string());
    }

    t.strip_prefix(GO_METAVAR_PREFIX)
        .filter(|name| {
            !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        })
        .map(|name| format!("${name}"))
}

fn is_ellipsis_pattern(text: &str) -> bool {
    matches!(text.trim(), "..." | GO_ELLIPSIS_PLACEHOLDER)
}

// ─── metavariable-type resolution ────────────────────────────────────────────

/// Convert a 1-based (line, byte-column) position — as stored in a
/// [`MetavarRange`] — back to a byte offset into `source`. Inverse of
/// [`byte_offset_to_position`] (columns are byte offsets within the line).
fn position_to_byte_offset(source: &str, line: usize, col: usize) -> Option<usize> {
    let mut idx = 0usize;
    for (current_line, l) in (1usize..).zip(source.split_inclusive('\n')) {
        if current_line == line {
            let off = idx + col.saturating_sub(1);
            return Some(off.min(source.len()));
        }
        idx += l.len();
    }
    None
}

/// Tree-sitter node kinds that introduce a lexical scope, used to bound where a
/// declaration is visible. Union across the supported statically-typed grammars.
const SCOPE_KINDS: &[&str] = &[
    // shared / block-like
    "block",
    "statement_block",
    "function_body",
    "constructor_body",
    "class_body",
    "declaration_list",
    "statements",
    "switch_block",
    "program",
    "source_file",
    "compilation_unit",
    // parameter-bearing declarations (so params are visible in their body)
    "method_declaration",
    "constructor_declaration",
    "function_declaration",
    "local_function_statement",
    "lambda_expression",
    // self-scoping statements whose header declares a variable
    "for_statement",
    "enhanced_for_statement",
    "for_each_statement",
    "catch_clause",
];

/// Byte range of the nearest enclosing scope for a declaration node. Falls back
/// to the whole file when no scope ancestor is found.
fn scope_range_for_decl(node: tree_sitter::Node) -> (usize, usize) {
    let mut n = node;
    while let Some(parent) = n.parent() {
        if SCOPE_KINDS.contains(&parent.kind()) {
            return (parent.start_byte(), parent.end_byte());
        }
        n = parent;
    }
    (0, usize::MAX)
}

/// Text of a type node, or `None` if absent/empty.
fn type_node_text<'a>(node: Option<tree_sitter::Node>, source: &'a str) -> Option<&'a str> {
    let n = node?;
    let text = &source[n.byte_range()];
    (!text.trim().is_empty()).then_some(text)
}

/// First child of `node` (recursively, breadth-first over direct children) whose
/// kind is `kind`.
fn find_child_of_kind<'a>(
    node: tree_sitter::Node<'a>,
    kind: &str,
) -> Option<tree_sitter::Node<'a>> {
    let mut cursor = node.walk();
    let found = node.children(&mut cursor).find(|c| c.kind() == kind);
    found
}

/// If `node` declares a variable/parameter named `name`, return its declared
/// type text together with the byte range over which the declaration is in
/// scope. Purely syntactic, per statically-typed grammar.
fn decl_type_for<'a>(
    lang: Language,
    node: tree_sitter::Node<'a>,
    source: &'a str,
    name: &str,
) -> Option<(&'a str, (usize, usize))> {
    let name_matches = |n: Option<tree_sitter::Node>| -> bool {
        n.map(|n| &source[n.byte_range()] == name).unwrap_or(false)
    };

    match lang {
        Language::Java => match node.kind() {
            "formal_parameter" | "spread_parameter" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            "catch_formal_parameter" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ct = find_child_of_kind(node, "catch_type")?;
                    let ty = type_node_text(Some(ct), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            "enhanced_for_statement" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    // Scope is the loop itself (header + body).
                    return Some((ty, (node.start_byte(), node.end_byte())));
                }
                None
            }
            "local_variable_declaration" | "field_declaration" => {
                let ty = type_node_text(node.child_by_field_name("type"), source)?;
                let mut cursor = node.walk();
                for declarator in node.children(&mut cursor) {
                    if declarator.kind() == "variable_declarator"
                        && name_matches(declarator.child_by_field_name("name"))
                    {
                        return Some((ty, scope_range_for_decl(node)));
                    }
                }
                None
            }
            _ => None,
        },
        Language::CSharp => match node.kind() {
            "parameter" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            "variable_declaration" => {
                let ty = type_node_text(node.child_by_field_name("type"), source)?;
                let mut cursor = node.walk();
                for declarator in node.children(&mut cursor) {
                    if declarator.kind() == "variable_declarator"
                        && name_matches(declarator.child_by_field_name("name"))
                    {
                        return Some((ty, scope_range_for_decl(node)));
                    }
                }
                None
            }
            _ => None,
        },
        Language::Go => match node.kind() {
            "parameter_declaration" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            "var_spec" | "const_spec" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            _ => None,
        },
        Language::Kotlin => match node.kind() {
            // Function value parameters and `val`/`var` bindings share the
            // `simple_identifier : user_type` shape (no field names).
            "parameter" | "variable_declaration" => {
                let ident = find_child_of_kind(node, "simple_identifier")?;
                if &source[ident.byte_range()] != name {
                    return None;
                }
                let ty = type_node_text(find_child_of_kind(node, "user_type"), source)?;
                Some((ty, scope_range_for_decl(node)))
            }
            _ => None,
        },
        // TypeScript (parsed under Language::JavaScript with the TS grammar).
        Language::JavaScript => match node.kind() {
            "required_parameter" | "optional_parameter" => {
                if name_matches(node.child_by_field_name("pattern")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            "variable_declarator" => {
                if name_matches(node.child_by_field_name("name")) {
                    let ty = type_node_text(node.child_by_field_name("type"), source)?;
                    return Some((ty, scope_range_for_decl(node)));
                }
                None
            }
            _ => None,
        },
        _ => None,
    }
}

/// Resolve the declared type (raw text) of the identifier `name` used at byte
/// `offset`, picking the innermost in-scope declaration. `None` when no
/// syntactic declaration is found.
fn resolve_declared_type(
    lang: Language,
    root: tree_sitter::Node,
    source: &str,
    name: &str,
    offset: usize,
) -> Option<String> {
    let mut best: Option<(usize, String)> = None;
    collect_declared_type(lang, root, source, name, offset, &mut best);
    best.map(|(_, ty)| ty)
}

fn collect_declared_type(
    lang: Language,
    node: tree_sitter::Node,
    source: &str,
    name: &str,
    offset: usize,
    best: &mut Option<(usize, String)>,
) {
    if let Some((ty, (scope_start, scope_end))) = decl_type_for(lang, node, source, name) {
        if offset >= scope_start && offset < scope_end {
            // Prefer the innermost scope (largest start byte).
            if best
                .as_ref()
                .map(|(s, _)| scope_start >= *s)
                .unwrap_or(true)
            {
                *best = Some((scope_start, ty.to_string()));
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_declared_type(lang, child, source, name, offset, best);
    }
}

/// Check if the pattern text is the special "..." (match-any-string) string literal.
fn is_any_string_pattern(text: &str) -> bool {
    let t = text.trim();
    t == "\"...\"" || t == "'...'"
}

/// Check if a target node is a string literal.
fn is_string_node(node: tree_sitter::Node, _source: &str) -> bool {
    matches!(
        node.kind(),
        "string"
            | "string_literal"
            | "interpreted_string_literal"
            | "raw_string_literal"
            | "template_string"
    )
}

fn byte_offset_to_position(source: &str, byte_offset: usize) -> (usize, usize) {
    let prefix = &source[..byte_offset];
    let line = prefix.bytes().filter(|b| *b == b'\n').count() + 1;
    let line_start = prefix.rfind('\n').map_or(0, |pos| pos + 1);
    let column = byte_offset - line_start + 1;
    (line, column)
}

/// Return the source text for a given 1-based line number, trimming the trailing newline.
/// Returns `None` if the line number is out of range.
fn find_source_line_by_line(source: &str, line: usize) -> Option<String> {
    source
        .lines()
        .nth(line.saturating_sub(1))
        .map(|s| s.to_string())
}

fn ranges_overlap(left: &MatchRange, right: &MatchRange) -> bool {
    left.start_byte < right.end_byte && right.start_byte < left.end_byte
}

fn merge_bindings(
    left: &HashMap<String, String>,
    right: &HashMap<String, String>,
) -> Option<HashMap<String, String>> {
    let mut merged = left.clone();

    for (key, value) in right {
        if let Some(existing) = merged.get(key) {
            if existing != value {
                return None;
            }
        } else {
            merged.insert(key.clone(), value.clone());
        }
    }

    Some(merged)
}

fn merge_binding_ranges(
    left: &HashMap<String, MetavarRange>,
    right: &HashMap<String, MetavarRange>,
) -> HashMap<String, MetavarRange> {
    let mut merged = left.clone();
    for (key, value) in right {
        merged.entry(key.clone()).or_insert(*value);
    }
    merged
}

fn intersect_match_sets(left: Vec<MatchRange>, right: Vec<MatchRange>) -> Vec<MatchRange> {
    let mut merged = Vec::new();

    for left_match in left {
        for right_match in &right {
            if !ranges_overlap(&left_match, right_match) {
                continue;
            }

            let Some(bindings) = merge_bindings(&left_match.bindings, &right_match.bindings) else {
                continue;
            };

            let binding_ranges =
                merge_binding_ranges(&left_match.binding_ranges, &right_match.binding_ranges);

            let mut combined = left_match.clone();
            combined.bindings = bindings;
            combined.binding_ranges = binding_ranges;
            merged.push(combined);
        }
    }

    merged.sort_by_key(|r| (r.start_byte, r.end_byte));
    merged.dedup_by_key(|r| (r.start_byte, r.end_byte));
    merged
}

fn match_negative_pattern(
    negative: &NegativeMatcher,
    root: tree_sitter::Node,
    source: &str,
) -> MatchResult {
    match negative {
        NegativeMatcher::Pattern(pattern) => match_single_pattern(pattern, root, source),
        NegativeMatcher::Regex(regex) => match_regex_pattern(regex, source),
    }
}

// ─── File Loading ───────────────────────────────────────────────────────────

fn map_severity(s: &SemgrepSeverity) -> Severity {
    match s {
        SemgrepSeverity::Error => Severity::Critical,
        SemgrepSeverity::Warning => Severity::High,
        // `MEDIUM` is used by some Semgrep registry packs (e.g. supply-chain rules).
        // Map to `High` to preserve the intent of "non-trivial risk"; foxguard
        // does not have a dedicated Medium->Medium mapping in its severity enum.
        SemgrepSeverity::Medium => Severity::High,
        SemgrepSeverity::Info => Severity::Medium,
    }
}

fn map_language(lang_str: &str) -> Option<Language> {
    match lang_str.to_lowercase().as_str() {
        "javascript" | "js" | "typescript" | "ts" | "jsx" | "tsx" => Some(Language::JavaScript),
        "python" | "py" => Some(Language::Python),
        "go" | "golang" => Some(Language::Go),
        "ruby" | "rb" => Some(Language::Ruby),
        "java" => Some(Language::Java),
        "php" => Some(Language::Php),
        "rust" | "rs" => Some(Language::Rust),
        "csharp" | "c#" | "cs" => Some(Language::CSharp),
        "swift" => Some(Language::Swift),
        "kotlin" | "kt" => Some(Language::Kotlin),
        "c" => Some(Language::C),
        "hcl" | "terraform" | "tf" => Some(Language::Hcl),
        "solidity" | "sol" => Some(Language::Solidity),
        "yaml" | "yml" => Some(Language::Yaml),
        "dockerfile" | "docker" => Some(Language::Dockerfile),
        "bash" | "sh" => Some(Language::Bash),
        "ocaml" | "ml" | "mli" => Some(Language::Ocaml),
        "scala" | "sc" => Some(Language::Scala),
        "elixir" | "ex" | "exs" => Some(Language::Elixir),
        "json" => Some(Language::Json),
        "apex" => Some(Language::Apex),
        "clojure" | "clj" | "cljs" | "cljc" => Some(Language::Clojure),
        "html" | "htm" => Some(Language::Html),
        "xml" => Some(Language::Xml),
        "dart" => Some(Language::Dart),
        "haskell" | "hs" => Some(Language::Haskell),
        _ => None,
    }
}

/// True when a rule's `languages` selects generic (spacegrep) matching.
/// Generic rules are AST-less and handled by [`crate::rules::generic_mode`].
///
/// Note: `languages: [regex]` is *not* generic mode — it is a distinct Semgrep
/// mode that runs pure `pattern-regex` against raw file bytes.  Those rules are
/// routed to [`build_regex_mode_rules`] instead.
fn is_generic_language_rule(languages: &[String]) -> bool {
    languages.iter().any(|l| l.to_lowercase() == "generic")
}

/// True when a rule targets Semgrep's pure-regex mode (`languages: [regex]`).
///
/// Regex-mode rules only support `pattern-regex` and `pattern-not-regex`; they
/// do not use a tree-sitter AST and are run against raw text on every file that
/// passes the rule's `paths:` filter.
fn is_regex_language_rule(languages: &[String]) -> bool {
    languages.iter().any(|l| l.to_lowercase() == "regex")
}

// ─── Regex-mode Rule ─────────────────────────────────────────────────────────

/// Every language the scanner can hand to a rule. A regex-mode rule is
/// language-agnostic and runs against every file's raw text, so we register one
/// rule instance per detectable language (fan-out mirrors the generic-mode
/// approach). The compiled matcher is shared via `Arc`, so the fan-out is cheap.
const REGEX_MODE_ALL_LANGUAGES: &[Language] = &[
    Language::JavaScript,
    Language::Python,
    Language::Go,
    Language::Ruby,
    Language::Java,
    Language::Php,
    Language::Rust,
    Language::CSharp,
    Language::Swift,
    Language::Kotlin,
    Language::C,
    Language::Hcl,
    Language::Solidity,
    Language::Yaml,
    Language::NginxConf,
    Language::ApacheConf,
    Language::HAProxyConf,
    Language::Dockerfile,
    Language::Manifest,
    Language::Bash,
    Language::Ocaml,
    Language::Scala,
    Language::Elixir,
    Language::Json,
    Language::Apex,
    Language::Clojure,
    Language::Html,
    Language::Xml,
    Language::Dart,
    Language::Haskell,
];

/// A compiled Semgrep `languages: [regex]` rule.
///
/// Regex-mode rules carry only `pattern-regex` / `pattern-not-regex` matchers
/// and are run against the raw text of every scanned file (no tree-sitter parse
/// required).  One rule instance is created per detectable language so the
/// existing `rule.language() == file_language` dispatch continues to work.
struct RegexModeRule {
    id: String,
    message: String,
    severity: Severity,
    cwe: Option<String>,
    /// Language this instance is registered under.
    lang: Language,
    /// The positive regex(es) — all must match at least once (AND semantics when
    /// multiple are present, matching Semgrep's `patterns:` AND-block behaviour).
    positives: std::sync::Arc<Vec<CompiledRegex>>,
    /// Negative regexes — if any match the entire file, the finding is suppressed.
    negatives: std::sync::Arc<Vec<CompiledRegex>>,
    path_filter: Option<std::sync::Arc<PathFilter>>,
}

impl Rule for RegexModeRule {
    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 applies_to_path(&self, path: &Path) -> bool {
        self.path_filter
            .as_ref()
            .is_none_or(|filter| filter.matches(path))
    }

    fn check(&self, source: &str, _tree: &tree_sitter::Tree) -> Vec<Finding> {
        // Run the positive regexes in intersection: each positive must produce
        // at least one match.  If any positive misses, the rule doesn't fire.
        let candidates: Option<Vec<MatchRange>> =
            self.positives
                .iter()
                .fold(None, |acc: Option<Vec<MatchRange>>, re| {
                    let hits: Vec<MatchRange> = match_regex_pattern(re, source);
                    Some(match acc {
                        None => hits,
                        Some(prev) => {
                            // Intersect: keep matches from `prev` that overlap with
                            // at least one match from `hits` (AND semantics across
                            // patterns: clauses, mirroring the AST Combined path).
                            prev.into_iter()
                                .filter(|p| {
                                    hits.iter().any(|h| {
                                        p.start_byte < h.end_byte && h.start_byte < p.end_byte
                                    })
                                })
                                .collect()
                        }
                    })
                });

        let mut results = candidates.unwrap_or_default();
        if results.is_empty() {
            return Vec::new();
        }

        // Apply negative filters: drop any positive match that overlaps with a
        // negative regex match anywhere in the file.
        for neg in self.negatives.iter() {
            let neg_hits: Vec<MatchRange> = match_regex_pattern(neg, source);
            if !neg_hits.is_empty() {
                results.retain(|r| {
                    !neg_hits
                        .iter()
                        .any(|n| r.start_byte < n.end_byte && n.start_byte < r.end_byte)
                });
            }
        }

        results
            .into_iter()
            .map(|m| Finding {
                rule_id: self.id.clone(),
                severity: self.severity,
                cwe: self.cwe.clone(),
                description: self.message.clone(),
                file: String::new(),
                line: m.line,
                column: m.column,
                end_line: m.end_line,
                end_column: m.end_column,
                snippet: m.snippet,
                source_line: None,
                source_description: None,
                sink_line: None,
                sink_description: None,
                fix_suggestion: None,
                sink_start_byte: None,
                sink_end_byte: None,
                confidence: 0.7,
                taint_hops: None,
                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![],
                crypto_material: None,
            })
            .collect()
    }
}

/// Compile a `languages: [regex]` rule into one [`RegexModeRule`] per
/// detectable language. Warns and returns an empty vec for rules that carry
/// only AST patterns (no `pattern-regex` anywhere).
fn build_regex_mode_rules(
    yaml: &SemgrepRuleYaml,
    severity: Severity,
    cwe: &Option<String>,
    path_filter: &Option<PathFilter>,
) -> Result<Vec<Box<dyn Rule>>, String> {
    // Collect all pattern-regex clauses from top-level AND from patterns: blocks.
    let mut positives: Vec<CompiledRegex> = Vec::new();
    let mut negatives: Vec<CompiledRegex> = Vec::new();

    // Helper: push a compiled regex or warn-skip if unsupported features are used.
    // Consistent with MetavariableRegexConstraint::from_yaml graceful degradation.
    macro_rules! push_regex {
        ($dest:expr, $re:expr, $label:expr) => {
            match compile_regex($re) {
                Ok(r) => $dest.push(r),
                Err(e) => eprintln!(
                    "Warning: regex-mode rule '{}' {} has unsupported regex ({}); \
                     skipping clause",
                    yaml.id, $label, e
                ),
            }
        };
    }

    // Top-level pattern-regex / pattern-not-regex.
    if let Some(ref re) = yaml.pattern_regex {
        push_regex!(positives, re, "pattern-regex");
    }
    if let Some(ref re) = yaml.pattern_not_regex {
        push_regex!(negatives, re, "pattern-not-regex");
    }

    // patterns: [...] blocks — collect pattern-regex / pattern-not-regex subclauses.
    if let Some(ref clauses) = yaml.patterns {
        for clause in clauses {
            if let Some(ref re) = clause.pattern_regex {
                push_regex!(positives, re, "patterns[].pattern-regex");
            }
            if let Some(ref re) = clause.pattern_not_regex {
                push_regex!(negatives, re, "patterns[].pattern-not-regex");
            }
            // Nested pattern-either entries may also carry pattern-regex.
            if let Some(ref entries) = clause.pattern_either {
                for entry in entries {
                    if let Some(ref re) = entry.pattern_regex {
                        push_regex!(positives, re, "patterns[].pattern-either[].pattern-regex");
                    }
                }
            }
        }
    }

    // Top-level pattern-either regex entries.
    if let Some(ref entries) = yaml.pattern_either {
        for entry in entries {
            if let Some(ref re) = entry.pattern_regex {
                push_regex!(positives, re, "pattern-either[].pattern-regex");
            }
        }
    }

    if positives.is_empty() {
        // Rule has no regex patterns at all (only AST patterns that regex mode
        // cannot execute). Warn-skip rather than build a no-op matcher.
        eprintln!(
            "Warning: languages: [regex] rule '{}' has no pattern-regex; \
             regex mode cannot run AST patterns — skipping",
            yaml.id
        );
        return Ok(Vec::new());
    }

    let positives = std::sync::Arc::new(positives);
    let negatives = std::sync::Arc::new(negatives);
    let path_filter = path_filter.clone().map(std::sync::Arc::new);

    let rules = REGEX_MODE_ALL_LANGUAGES
        .iter()
        .map(|&lang| {
            Box::new(RegexModeRule {
                id: format!("semgrep/{}", yaml.id),
                message: yaml.message.clone(),
                severity,
                cwe: cwe.clone(),
                lang,
                positives: std::sync::Arc::clone(&positives),
                negatives: std::sync::Arc::clone(&negatives),
                path_filter: path_filter.clone(),
            }) as Box<dyn Rule>
        })
        .collect();

    Ok(rules)
}

/// Compile a generic-mode rule via [`crate::rules::generic_mode`]. Thin
/// adapter: pulls the supported generic-mode fields off the YAML and delegates
/// all matching logic to that module.
///
/// Mapping from YAML → [`GenericRuleSpec`]:
/// - Top-level `pattern` / `pattern-regex` / `pattern-either` / `pattern-not` /
///   `pattern-not-regex` are forwarded as-is.
/// - `patterns:` AND-blocks are mapped clause-by-clause into
///   [`GenericPatternsClause`] structs; unsupported sub-clauses (e.g.
///   `pattern-inside`, `metavariable-*`) are warn-skipped without aborting
///   the rest of the rule.
fn build_generic_mode_rules(
    yaml: &SemgrepRuleYaml,
    severity: Severity,
    cwe: &Option<String>,
    path_filter: &Option<PathFilter>,
) -> Result<Vec<Box<dyn Rule>>, String> {
    use crate::rules::generic_mode::{
        build_generic_rules, GenericEitherEntry, GenericPatternsClause, GenericRuleSpec,
    };

    // Map one `patterns:` clause into a generic clause, preserving the
    // metavariable constraints + focus that operate over named regex captures.
    // Returns `None` for clauses with no expressible content (pattern-inside /
    // pattern-not-inside / empty) so they are warn-skipped without aborting.
    //
    // `strict` is set for clauses inside a `pattern-either` arm that is a nested
    // `patterns:` AND-block (the new package-manager rule shape). In strict mode,
    // a clause carrying an unenforceable constraint (metavariable-pattern /
    // metavariable-analysis) flags the block as unbuildable so the arm is
    // warn-skipped rather than loaded broadened. For top-level `patterns:`
    // blocks (`strict == false`) we preserve the established
    // load-with-dropped-constraint behaviour to avoid regressing rules that
    // already loaded that way.
    fn map_clause(
        clause: &PatternClause,
        rule_id: &str,
        strict: bool,
    ) -> Option<GenericPatternsClause> {
        if clause.pattern_inside.is_some() {
            eprintln!(
                "Warning: generic mode does not support pattern-inside in rule '{rule_id}'; \
                 skipping clause"
            );
            return None;
        }
        if clause.pattern_not_inside.is_some() {
            eprintln!(
                "Warning: generic mode does not support pattern-not-inside in rule '{rule_id}'; \
                 skipping clause"
            );
            return None;
        }
        let pattern_either_entries: Vec<GenericEitherEntry> = clause
            .pattern_either
            .iter()
            .flatten()
            .map(map_either_arm)
            .collect();

        let metavariable_regex = clause
            .metavariable_regex
            .as_ref()
            .map(|mr| (mr.metavariable.clone(), mr.regex.clone()));
        let metavariable_comparison = clause
            .metavariable_comparison
            .as_ref()
            .map(|mc| (mc.metavariable.clone(), mc.comparison.clone()));
        let focus_metavariable = clause
            .focus_metavariable
            .clone()
            .and_then(|f| f.into_vec().into_iter().next());

        // metavariable-pattern / metavariable-analysis cannot be enforced in
        // generic mode. In strict mode (a `pattern-either` arm), flag the clause
        // so its `patterns:` block refuses to load — dropping the constraint
        // would broaden the rule into false positives. In lenient mode
        // (top-level `patterns:`), keep the legacy load-broadened behaviour.
        let unsupported_constraint = strict
            && (clause.metavariable_pattern.is_some() || clause.metavariable_analysis.is_some());

        let has_positive = clause.pattern.is_some()
            || clause.pattern_regex.is_some()
            || !pattern_either_entries.is_empty();
        let has_negative = clause.pattern_not.is_some() || clause.pattern_not_regex.is_some();
        let has_constraint = metavariable_regex.is_some()
            || metavariable_comparison.is_some()
            || focus_metavariable.is_some()
            || unsupported_constraint;

        if !has_positive && !has_negative && !has_constraint {
            return None;
        }

        Some(GenericPatternsClause {
            pattern: clause.pattern.clone(),
            pattern_regex: clause.pattern_regex.clone(),
            pattern_either: pattern_either_entries,
            pattern_not: clause.pattern_not.clone(),
            pattern_not_regex: clause.pattern_not_regex.clone(),
            metavariable_regex,
            metavariable_comparison,
            focus_metavariable,
            unsupported_constraint,
        })
    }

    // Map one `pattern-either` arm. An arm is either a simple pattern/regex or a
    // nested `patterns:` AND-block (the package-manager rule shape).
    fn map_either_arm(entry: &PatternEntry) -> GenericEitherEntry {
        // Decode the raw `patterns:` value into typed clauses leniently. If it
        // does not fit our `PatternClause` shape (e.g. an AST-only nested form),
        // we simply skip it — the arm degrades to its `pattern`/`pattern-regex`
        // (usually empty), which the generic builder warn-skips.
        let patterns = entry
            .patterns
            .as_ref()
            .and_then(|v| serde_yaml_ng::from_value::<Vec<PatternClause>>(v.clone()).ok())
            .unwrap_or_default()
            .iter()
            .filter_map(|c| map_clause(c, "<pattern-either arm>", true))
            .collect();
        GenericEitherEntry {
            pattern: entry.pattern.clone(),
            pattern_regex: entry.pattern_regex.clone(),
            patterns,
        }
    }

    // Top-level pattern-either: simple `pattern:` / `pattern-regex:` arms and
    // nested `patterns:` AND-block arms are all forwarded.
    let pattern_either: Vec<GenericEitherEntry> = yaml
        .pattern_either
        .iter()
        .flatten()
        .map(map_either_arm)
        .collect();

    // Map top-level `patterns:` clauses.
    let patterns_clauses: Vec<GenericPatternsClause> = yaml
        .patterns
        .iter()
        .flatten()
        .filter_map(|clause| map_clause(clause, &yaml.id, false))
        .collect();

    build_generic_rules(GenericRuleSpec {
        id: &yaml.id,
        message: &yaml.message,
        severity,
        cwe: cwe.clone(),
        pattern: yaml.pattern.as_deref(),
        pattern_regex: yaml.pattern_regex.as_deref(),
        pattern_either,
        pattern_not: yaml.pattern_not.as_deref(),
        pattern_not_regex: yaml.pattern_not_regex.as_deref(),
        patterns_clauses,
        path_filter: path_filter.clone(),
    })
}

fn build_matcher(yaml: &SemgrepRuleYaml, lang: Language) -> Result<PatternMatcher, String> {
    // Combined patterns (AND)
    if let Some(ref clauses) = yaml.patterns {
        let mut positives = Vec::new();
        let mut negatives = Vec::new();
        let mut inside = None;
        let mut not_inside = None;
        let mut metavariable_regexes = Vec::new();
        let mut metavariable_comparisons = Vec::new();
        let mut metavariable_patterns = Vec::new();
        let mut metavariable_analyses = Vec::new();
        let mut metavariable_types = Vec::new();
        let mut focus_metavariables: Vec<String> = Vec::new();

        for clause in clauses {
            if let Some(ref p) = clause.pattern {
                positives.push(PatternMatcher::Single(CompiledAstPattern::new(
                    p.clone(),
                    lang,
                )));
            }
            if let Some(ref regex) = clause.pattern_regex {
                // Gracefully skip individual pattern-regex clauses that use
                // unsupported features (lookahead/lookbehind, backreferences,
                // etc.) — consistent with MetavariableRegexConstraint::from_yaml.
                // The sibling clauses are unaffected; the rule loads with a
                // broader but functional matcher.
                match compile_regex(regex) {
                    Ok(r) => positives.push(PatternMatcher::Regex(r)),
                    Err(e) => eprintln!(
                        "Warning: patterns: clause has unsupported pattern-regex ({}); \
                         skipping clause",
                        e
                    ),
                }
            }
            if let Some(ref pn) = clause.pattern_not {
                negatives.push(NegativeMatcher::Pattern(CompiledAstPattern::new(
                    pn.clone(),
                    lang,
                )));
            }
            if let Some(ref regex) = clause.pattern_not_regex {
                // Gracefully skip unsupported negative-regex clauses too.
                match compile_regex(regex) {
                    Ok(r) => negatives.push(NegativeMatcher::Regex(r)),
                    Err(e) => eprintln!(
                        "Warning: patterns: clause has unsupported pattern-not-regex ({}); \
                         skipping clause",
                        e
                    ),
                }
            }
            if let Some(ref pi) = clause.pattern_inside {
                inside = Some(CompiledAstPattern::new(pi.clone(), lang));
            }
            if let Some(pni) = clause.pattern_not_inside.clone() {
                if let Some(pat_str) = pni.into_pattern_string() {
                    not_inside = Some(CompiledAstPattern::new(pat_str, lang));
                }
                // If into_pattern_string returns None it already printed a warning;
                // the constraint is gracefully skipped.
            }
            if let Some(ref pe) = clause.pattern_either {
                let matchers = build_either_matchers(pe, lang)?;
                positives.push(PatternMatcher::Either(matchers));
            }
            if let Some(ref mr) = clause.metavariable_regex {
                if let Some(constraint) = MetavariableRegexConstraint::from_yaml(mr) {
                    metavariable_regexes.push(constraint);
                }
                // If from_yaml returns None it already printed a warning; we
                // continue loading the rest of the rule's clauses.
            }
            if let Some(ref mc) = clause.metavariable_comparison {
                match MetavariableComparisonConstraint::from_yaml(mc) {
                    Ok(constraint) => metavariable_comparisons.push(constraint),
                    Err(e) => eprintln!("Warning: {e}"),
                }
            }
            if let Some(ref mp) = clause.metavariable_pattern {
                if let Some(constraint) = MetavariablePatternConstraint::from_yaml(mp, lang) {
                    metavariable_patterns.push(constraint);
                }
                // If from_yaml returns None it already printed a warning; we
                // continue loading the rest of the rule's clauses.
            }
            if let Some(ref ma) = clause.metavariable_analysis {
                if let Some(constraint) = MetavariableAnalysisConstraint::from_yaml(ma) {
                    metavariable_analyses.push(constraint);
                }
                // If from_yaml returns None it already printed a warning; we
                // continue loading the rest of the rule's clauses.
            }
            if let Some(ref mt) = clause.metavariable_type {
                // FAITHFULNESS: a `metavariable-type:` constraint we cannot
                // enforce must not be silently dropped — that would broaden the
                // rule into an over-match. For languages without syntactic type
                // resolution we skip the whole rule instead.
                if !metavariable_type_enforceable(lang) {
                    return Err(format!(
                        "metavariable-type on {} is not enforceable for {} \
                         (no syntactic type resolution); skipping rule",
                        mt.metavariable, lang
                    ));
                }
                metavariable_types.push(MetavariableTypeConstraint::from_yaml(mt, lang));
            }
            if let Some(ref fmv) = clause.focus_metavariable {
                focus_metavariables.extend(fmv.clone().into_vec());
            }
        }

        return Ok(PatternMatcher::Combined {
            positives,
            negatives,
            inside,
            not_inside,
            metavariable_regexes,
            metavariable_comparisons,
            metavariable_patterns,
            metavariable_analyses,
            metavariable_types,
            focus_metavariables,
        });
    }

    let mut positives = Vec::new();
    let mut negatives = Vec::new();

    if let Some(ref pat) = yaml.pattern {
        positives.push(PatternMatcher::Single(CompiledAstPattern::new(
            pat.clone(),
            lang,
        )));
    }
    if let Some(ref regex) = yaml.pattern_regex {
        // Gracefully skip unsupported top-level pattern-regex.
        match compile_regex(regex) {
            Ok(r) => positives.push(PatternMatcher::Regex(r)),
            Err(e) => eprintln!(
                "Warning: top-level pattern-regex uses unsupported features ({}); \
                 skipping pattern",
                e
            ),
        }
    }
    if let Some(ref either) = yaml.pattern_either {
        positives.push(PatternMatcher::Either(build_either_matchers(either, lang)?));
    }
    if let Some(ref pat) = yaml.pattern_not {
        negatives.push(NegativeMatcher::Pattern(CompiledAstPattern::new(
            pat.clone(),
            lang,
        )));
    }
    if let Some(ref regex) = yaml.pattern_not_regex {
        // Gracefully skip unsupported top-level pattern-not-regex.
        match compile_regex(regex) {
            Ok(r) => negatives.push(NegativeMatcher::Regex(r)),
            Err(e) => eprintln!(
                "Warning: top-level pattern-not-regex uses unsupported features ({}); \
                 skipping pattern",
                e
            ),
        }
    }

    // Extract the `pattern-not-inside` string from either the literal or block form.
    // `PatternOrBlock::into_pattern_string` is a consuming method; we clone so
    // the borrow checker is happy.
    let not_inside_pat: Option<CompiledAstPattern> =
        yaml.pattern_not_inside.clone().and_then(|pob| {
            pob.into_pattern_string()
                .map(|pat| CompiledAstPattern::new(pat, lang))
        });

    if positives.len() == 1
        && negatives.is_empty()
        && yaml.pattern_inside.is_none()
        && not_inside_pat.is_none()
    {
        return Ok(positives.into_iter().next().expect("checked len == 1"));
    }

    if !positives.is_empty() {
        return Ok(PatternMatcher::Combined {
            positives,
            negatives,
            inside: yaml
                .pattern_inside
                .as_ref()
                .map(|pattern| CompiledAstPattern::new(pattern.clone(), lang)),
            not_inside: not_inside_pat,
            metavariable_regexes: Vec::new(),
            metavariable_comparisons: Vec::new(),
            metavariable_patterns: Vec::new(),
            metavariable_analyses: Vec::new(),
            metavariable_types: Vec::new(),
            focus_metavariables: Vec::new(),
        });
    }

    // Fallback: empty matcher that matches nothing
    Ok(PatternMatcher::Either(Vec::new()))
}

fn build_either_matchers(
    entries: &[PatternEntry],
    lang: Language,
) -> Result<Vec<PatternMatcher>, String> {
    let mut matchers = Vec::new();

    for entry in entries {
        if let Some(ref pattern) = entry.pattern {
            matchers.push(PatternMatcher::Single(CompiledAstPattern::new(
                pattern.clone(),
                lang,
            )));
        }
        if let Some(ref regex) = entry.pattern_regex {
            // Gracefully skip individual pattern-regex entries that use
            // unsupported features (lookahead/lookbehind, backreferences, etc.)
            // — consistent with MetavariableRegexConstraint::from_yaml.  The
            // remaining entries in the pattern-either list are still compiled;
            // the rule loads with a broader but functional matcher.
            match compile_regex(regex) {
                Ok(r) => matchers.push(PatternMatcher::Regex(r)),
                Err(e) => eprintln!(
                    "Warning: pattern-either entry has unsupported pattern-regex ({}); \
                     skipping entry",
                    e
                ),
            }
        }
    }

    Ok(matchers)
}

pub(crate) fn compile_regex(pattern: &str) -> Result<CompiledRegex, String> {
    // `\Z` is a Python/PCRE end-of-string anchor meaning "end of string before
    // optional trailing newline".  The Rust `regex` crate uses `$` with the
    // `MULTILINE` flag off for the same semantics (match at absolute end).
    // We normalise it here so rules that use `\Z` load successfully.
    let normalised = pattern.replace(r"\Z", "$");

    // The Rust `regex` crate is stricter than PCRE/Python `re` about bare `{`.
    // In PCRE, a `{` not followed by a valid quantifier `{N}`, `{N,}`, or
    // `{N,M}` is treated as a literal brace.  In Rust's `regex` crate it
    // causes a hard parse error ("repetition operator missing expression" or
    // "repetition quantifier expects a valid decimal").  Many Semgrep registry
    // rules written for PCRE contain template-syntax patterns like `{{` or
    // `{%` that use literal braces without escaping.  We apply a conservative
    // normalisation pass that escapes any `{` not already escaped and not
    // followed by a valid quantifier body.
    let normalised = escape_bare_braces(&normalised);

    // Fast path: the linear-time `regex` crate handles the overwhelming
    // majority of patterns.  Keep it as the primary engine.
    match Regex::new(&normalised) {
        Ok(re) => Ok(CompiledRegex::Fast(re)),
        // Fallback path: the `regex` crate rejected the pattern.  This is the
        // case for PCRE features it deliberately does not support —
        // lookahead `(?=...)`/`(?!...)`, lookbehind `(?<=...)`/`(?<!...)`, and
        // named/numeric backreferences.  The backtracking `fancy-regex`
        // engine supports these, so we retry there before giving up.
        Err(fast_err) => match fancy_regex::Regex::new(&normalised) {
            Ok(re) => Ok(CompiledRegex::Fancy(re)),
            Err(fancy_err) => Err(format!(
                "Invalid pattern-regex '{}': {} (fancy-regex fallback also failed: {})",
                pattern, fast_err, fancy_err
            )),
        },
    }
}

/// Escape bare `{` characters that Rust's `regex` crate would reject as
/// invalid quantifier-start tokens.
///
/// A `{` is a valid quantifier start when it is:
/// - preceded by an even number of backslashes (i.e. not already escaped), and
/// - followed by one or two decimal sequences matching `N` or `N,M`.
///
/// Any `{` not matching that shape is escaped to `\{`.  This converts
/// PCRE-style template patterns like `{{` (Django/Flask/Jinja) or `{%`
/// (template tag) into the `\{\{` / `\{%` forms that Rust's `regex` crate
/// accepts without changing any valid quantifiers such as `{20}` or `{1,3}`.
fn escape_bare_braces(s: &str) -> String {
    // We walk byte-by-byte, tracking:
    //   - whether the previous byte was a backslash (escape tracking)
    //   - whether we're inside a character class `[...]` (quantifiers are
    //     literal inside classes)
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut out = String::with_capacity(n + 8);
    let mut i = 0;
    let mut backslash_run = 0usize; // number of consecutive preceding backslashes
    let mut in_class = false; // inside [...]

    while i < n {
        let b = bytes[i];

        match b {
            b'\\' => {
                backslash_run += 1;
                out.push(b as char);
                i += 1;
            }
            b'[' if backslash_run.is_multiple_of(2) => {
                in_class = true;
                backslash_run = 0;
                out.push('[');
                i += 1;
            }
            b']' if backslash_run.is_multiple_of(2) => {
                in_class = false;
                backslash_run = 0;
                out.push(']');
                i += 1;
            }
            b'{' if backslash_run.is_multiple_of(2) && !in_class => {
                backslash_run = 0;
                // Peek ahead: is this a valid quantifier `{N}`, `{N,}`, `{N,M}`?
                if looks_like_quantifier(bytes, i + 1) {
                    out.push('{');
                } else {
                    // Not a valid quantifier — escape it.
                    out.push_str(r"\{");
                }
                i += 1;
            }
            b'}' if backslash_run.is_multiple_of(2) && !in_class => {
                backslash_run = 0;
                // A `}` that closes a `{` we already escaped (or a stray `}`)
                // should also be escaped.  We do this conservatively: only
                // escape `}` when it is NOT immediately closing a valid
                // quantifier opened in the pattern.  Since we rewrote all
                // non-quantifier `{` above, any remaining unmatched `}` is
                // also bare and should be `\}`.
                //
                // Simple heuristic: `}` not preceded by digits or `,` + digit
                // is treated as a stray closing brace and escaped.
                let prev = out.as_bytes().last().copied();
                if matches!(prev, Some(b'0'..=b'9') | Some(b',') | Some(b'{')) {
                    // Looks like it closes a quantifier we left open — leave as-is.
                    out.push('}');
                } else {
                    out.push_str(r"\}");
                }
                i += 1;
            }
            _ => {
                backslash_run = 0;
                out.push(b as char);
                i += 1;
            }
        }
    }

    out
}

/// Returns `true` when the bytes starting at `pos` look like the inside of a
/// valid regex quantifier: `N}`, `N,}`, or `N,M}` where N and M are decimal
/// integers.
fn looks_like_quantifier(bytes: &[u8], pos: usize) -> bool {
    let n = bytes.len();
    let mut i = pos;

    // At least one digit required.
    if i >= n || !bytes[i].is_ascii_digit() {
        return false;
    }
    while i < n && bytes[i].is_ascii_digit() {
        i += 1;
    }
    if i >= n {
        return false;
    }

    match bytes[i] {
        b'}' => true, // `{N}`
        b',' => {
            i += 1;
            // Optional second number.
            while i < n && bytes[i].is_ascii_digit() {
                i += 1;
            }
            i < n && bytes[i] == b'}'
        }
        _ => false,
    }
}

fn compile_globset(patterns: &[String]) -> Result<Option<GlobSet>, String> {
    if patterns.is_empty() {
        return Ok(None);
    }

    let mut builder = GlobSetBuilder::new();
    for pattern in patterns {
        let glob =
            Glob::new(pattern).map_err(|e| format!("Invalid paths glob '{}': {}", pattern, e))?;
        builder.add(glob);
    }

    builder
        .build()
        .map(Some)
        .map_err(|e| format!("Failed to build paths globset: {}", e))
}

fn normalize_rule_path(path: &Path) -> String {
    path.components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

fn extract_cwe(yaml: &SemgrepRuleYaml) -> Option<String> {
    let meta = yaml.metadata.as_ref()?;
    let cwe = meta.cwe.as_ref()?;
    match cwe {
        CweValue::Single(s) => Some(s.clone()),
        CweValue::List(v) => v.first().cloned(),
    }
}

fn reserved_rule_namespace(rule_id: &str) -> Option<&'static str> {
    let (namespace, _) = rule_id.split_once('/')?;
    RESERVED_RULE_ID_NAMESPACES
        .iter()
        .copied()
        .find(|reserved| *reserved == namespace)
}

fn validate_semgrep_rule_id(rule_id: &str, source_label: &str) -> Result<(), String> {
    let Some(namespace) = reserved_rule_namespace(rule_id) else {
        return Ok(());
    };

    Err(format!(
        "Rule id '{}' in {} uses reserved namespace '{}/'. YAML rule packs must use a pack-specific namespace such as 'kernel/dirty-frag/...' or 'acme/security/...'. Reserved namespaces: {}",
        rule_id,
        source_label,
        namespace,
        RESERVED_RULE_ID_NAMESPACES.join(", ")
    ))
}

/// Parse a single Semgrep YAML file into foxguard rules.
pub fn parse_semgrep_file(path: &Path) -> Result<Vec<Box<dyn Rule>>, String> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    parse_semgrep_str(&content, &path.display().to_string())
}

/// Parse a Semgrep YAML document (passed as an in-memory string) into
/// foxguard rules.
///
/// This sibling of [`parse_semgrep_file`] exists so the registry can load
/// bundled rule packs embedded into the binary at compile time
/// (`include_dir!` blobs have no filesystem path). `source_label` is used
/// purely for error messages — pass the embedded path or any human-readable
/// identifier.
pub fn parse_semgrep_str(content: &str, source_label: &str) -> Result<Vec<Box<dyn Rule>>, String> {
    use crate::rules::semgrep_taint::{self, TaintRuleParse};
    use serde_yaml_ng::Value as YamlValue;

    // First pass: parse as an untyped Value so we can detect `mode: taint`
    // rules and route them to the taint bridge without breaking the strict
    // `SemgrepRuleYaml` schema used for pattern rules.
    let raw_doc: YamlValue = serde_yaml_ng::from_str(content)
        .map_err(|e| format!("Failed to parse YAML {}: {}", source_label, e))?;

    let mut rules: Vec<Box<dyn Rule>> = Vec::new();
    let mut pattern_rule_nodes: Vec<YamlValue> = Vec::new();

    if let Some(raw_rules) = raw_doc.get("rules").and_then(YamlValue::as_sequence) {
        for raw_rule in raw_rules {
            if let Some(rule_id) = raw_rule.get("id").and_then(YamlValue::as_str) {
                validate_semgrep_rule_id(rule_id, source_label)?;
            }

            if raw_rule
                .get("engine")
                .and_then(YamlValue::as_str)
                .is_some_and(|engine| {
                    engine.eq_ignore_ascii_case("coccinelle")
                        || engine.eq_ignore_ascii_case("codeql")
                })
            {
                continue;
            }

            match semgrep_taint::parse_taint_rule(raw_rule) {
                TaintRuleParse::Compiled(r) => rules.push(Box::new(r)),
                TaintRuleParse::Skip(msg) => eprintln!("Warning: {}", msg),
                TaintRuleParse::NotTaint => pattern_rule_nodes.push(raw_rule.clone()),
            }
        }
    }

    // Second pass: the non-taint rules go through the existing strict
    // deserialization path. Re-serialize them into a minimal `SemgrepFile`
    // so we reuse `build_matcher`, path filters, language mapping, etc.
    let pattern_file = YamlValue::Mapping({
        let mut m = serde_yaml_ng::Mapping::new();
        m.insert(
            YamlValue::String("rules".into()),
            YamlValue::Sequence(pattern_rule_nodes),
        );
        m
    });
    let semgrep_file: SemgrepFile = serde_yaml_ng::from_value(pattern_file)
        .map_err(|e| format!("Failed to parse YAML {}: {}", source_label, e))?;

    for yaml_rule in semgrep_file.rules {
        let cwe = extract_cwe(&yaml_rule);
        let severity = map_severity(&yaml_rule.severity);
        let path_filter = PathFilter::from_yaml(yaml_rule.paths.as_ref())?;

        // `languages: [generic]` — AST-less spacegrep rules routed to the
        // generic-mode (tokenized) matcher.  See `generic_mode.rs`.
        if is_generic_language_rule(&yaml_rule.languages) {
            rules.extend(build_generic_mode_rules(
                &yaml_rule,
                severity,
                &cwe,
                &path_filter,
            )?);
            continue;
        }

        // `languages: [regex]` — pure regex rules that run `pattern-regex` /
        // `pattern-not-regex` against raw file text, with no tree-sitter parse.
        // They are language-agnostic and fan out across all detectable languages.
        if is_regex_language_rule(&yaml_rule.languages) {
            rules.extend(build_regex_mode_rules(
                &yaml_rule,
                severity,
                &cwe,
                &path_filter,
            )?);
            continue;
        }

        let mut mapped_languages = Vec::new();
        for lang_str in &yaml_rule.languages {
            if let Some(lang) = map_language(lang_str) {
                if !mapped_languages.contains(&lang) {
                    mapped_languages.push(lang);
                }
            }
        }

        for lang in mapped_languages {
            let matcher = build_matcher(&yaml_rule, lang)?;
            rules.push(Box::new(SemgrepRule {
                id: format!("semgrep/{}", yaml_rule.id),
                message: yaml_rule.message.clone(),
                severity,
                lang,
                cwe: cwe.clone(),
                matcher,
                path_filter: path_filter.clone(),
                fix_template: yaml_rule.fix.clone(),
            }));
        }
    }

    Ok(rules)
}

/// Load all Semgrep YAML rules from a file or directory (recursive).
pub fn load_semgrep_rules(path: &Path) -> Vec<Box<dyn Rule>> {
    let mut rules = Vec::new();

    if path.is_file() {
        match parse_semgrep_file(path) {
            Ok(r) => rules.extend(r),
            Err(e) => eprintln!("Warning: {}", e),
        }
    } else if path.is_dir() {
        let walker = walkdir::WalkDir::new(path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.file_type().is_file()
                    && matches!(
                        e.path().extension().and_then(|s| s.to_str()),
                        Some("yaml" | "yml")
                    )
            });

        for entry in walker {
            match parse_semgrep_file(entry.path()) {
                Ok(r) => rules.extend(r),
                Err(e) => eprintln!("Warning: {}", e),
            }
        }
    }

    rules
}

/// Load all Semgrep YAML rules from an embedded [`include_dir::Dir`] tree.
///
/// Used for the rule packs that ship inside the `foxguard` binary
/// (currently `rules/kernel/dirty-frag-class/`). Walks the tree
/// recursively, picks up every `.yaml` / `.yml` file, and parses each as a
/// Semgrep document. CodeQL-engine rules are skipped inside
/// `parse_semgrep_str` (handled by the separate CodeQL bridge), so it is
/// safe to pass mixed packs.
pub fn load_semgrep_rules_from_embedded(dir: &include_dir::Dir<'_>) -> Vec<Box<dyn Rule>> {
    let mut rules = Vec::new();
    walk_embedded_dir(dir, &mut rules);
    rules
}

fn walk_embedded_dir(dir: &include_dir::Dir<'_>, rules: &mut Vec<Box<dyn Rule>>) {
    for file in dir.files() {
        let path = file.path();
        let ext = path.extension().and_then(|s| s.to_str());
        if !matches!(ext, Some("yaml" | "yml")) {
            continue;
        }
        let Some(content) = file.contents_utf8() else {
            eprintln!(
                "Warning: embedded rule {} is not valid UTF-8, skipping",
                path.display()
            );
            continue;
        };
        let label = format!("<bundled:{}>", path.display());
        match parse_semgrep_str(content, &label) {
            Ok(r) => rules.extend(r),
            Err(e) => eprintln!("Warning: {e}"),
        }
    }
    for subdir in dir.dirs() {
        // `queries/` subtrees hold CodeQL `.ql` files plus `qlpack.yml` /
        // `codeql-pack.lock.yml` pack metadata. Those `.yml` files match
        // our extension filter but are NOT Semgrep rules — they belong to
        // the CodeQL bridge. Skip the whole subtree so we don't print
        // spurious parse warnings at startup.
        if subdir.path().file_name().and_then(|s| s.to_str()) == Some("queries") {
            continue;
        }
        walk_embedded_dir(subdir, rules);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn make_yaml(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    #[test]
    fn test_parse_simple_rule() {
        let yaml = r#"
rules:
  - id: test-eval
    pattern: eval(...)
    message: Do not use eval
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].id(), "semgrep/test-eval");
        assert_eq!(rules[0].severity(), Severity::Critical);
    }

    #[test]
    fn test_reserved_rule_id_namespace_is_rejected() {
        let yaml = r#"
rules:
  - id: py/custom-eval
    pattern: eval(...)
    message: Do not use eval
    severity: ERROR
    languages: [python]
"#;

        let err = match parse_semgrep_str(yaml, "org-pack.yml") {
            Ok(_) => panic!("reserved rule namespace should be rejected"),
            Err(err) => err,
        };
        assert!(err.contains("py/custom-eval"));
        assert!(err.contains("reserved namespace 'py/'"));
        assert!(err.contains("org-pack.yml"));
    }

    #[test]
    fn test_reserved_rule_id_alias_namespaces_are_rejected() {
        for namespace in ["cs", "csharp", "rs", "rust"] {
            let rule_id = format!("{namespace}/custom-rule");
            assert_eq!(reserved_rule_namespace(&rule_id), Some(namespace));
        }
    }

    #[test]
    fn ast_patterns_are_compiled_during_rule_load() {
        let yaml = r#"
rules:
  - id: test-eval
    pattern: eval(...)
    message: Do not use eval
    severity: ERROR
    languages: [python]
"#;
        let parsed: SemgrepFile = serde_yaml_ng::from_str(yaml).unwrap();
        let matcher = build_matcher(&parsed.rules[0], Language::Python).unwrap();

        match matcher {
            PatternMatcher::Single(pattern) => {
                assert!(pattern.tree.is_some());
                assert_eq!(pattern.selector_kind.as_deref(), Some("call"));
            }
            other => panic!("expected single compiled AST pattern, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_pattern_either() {
        let yaml = r#"
rules:
  - id: dangerous-funcs
    pattern-either:
      - pattern: eval(...)
      - pattern: exec(...)
    message: Dangerous function
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1);
    }

    #[test]
    fn test_dedup_mapped_languages() {
        let yaml = r#"
rules:
  - id: js-send
    pattern: res.send("Hello World")
    message: Exact Express response send call
    severity: WARNING
    languages: [javascript, typescript]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].language(), Language::JavaScript);
    }

    #[test]
    fn test_metavar_detection() {
        assert!(is_metavar("$VAR"));
        assert!(is_metavar("$X"));
        assert!(is_metavar("$DB_NAME"));
        assert!(!is_metavar("$"));
        assert!(!is_metavar("foo"));
        assert!(!is_metavar("$foo.bar"));
    }

    #[test]
    fn test_match_eval_pattern() {
        let yaml = r#"
rules:
  - id: test-eval
    pattern: eval(...)
    message: No eval
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "x = eval(user_input)\ny = safe_func()\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn semgrep_compat_findings_are_emitted_at_confidence_zero_point_seven() {
        // External Semgrep-compat rules default to confidence=0.7
        // because pattern rules are inherently fuzzier than curated
        // built-in AST-walked rules. See issue #207.
        let yaml = r#"
rules:
  - id: test-eval
    pattern: eval(...)
    message: No eval
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "x = eval(user_input)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert!((findings[0].confidence - 0.7).abs() < f32::EPSILON);
    }

    #[test]
    fn test_match_hardcoded_string() {
        let yaml = r#"
rules:
  - id: hardcoded-password
    pattern: password = "..."
    message: Hardcoded password
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "password = \"supersecret\"\nusername = \"admin\"\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn test_match_string_concat_with_metavar() {
        let yaml = r#"
rules:
  - id: string-concat
    pattern: '"..." + $VAR'
    message: String concatenation
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "query = \"SELECT \" + user_input\nsafe = 1 + 2\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn test_match_pattern_regex() {
        let yaml = r#"
rules:
  - id: regex-secret
    pattern-regex: "(?m)^SECRET_KEY\\s*="
    message: Regex secret
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "password = \"supersecret\"\nSECRET_KEY = \"django-secret\"\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 2);
    }

    #[test]
    fn test_pattern_not_regex_filters_matches() {
        let yaml = r#"
rules:
  - id: password-assign
    patterns:
      - pattern-regex: "(?m)^.*password.*="
      - pattern-not-regex: "not_password"
    message: Password assignment
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "password = \"supersecret\"\nnot_password = \"safe\"\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn test_metavariable_regex_filters_bound_matches() {
        let yaml = r#"
rules:
  - id: user-input-only
    patterns:
      - pattern: '"..." + $VAR'
      - metavariable-regex:
          metavariable: $VAR
          regex: ^user_input$
    message: user input only
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "query = \"SELECT \" + user_input\nquery2 = \"SELECT \" + safe_value\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn test_pattern_not_inside_excludes_nested_matches() {
        let yaml = r#"
rules:
  - id: redirect-outside-helpers
    patterns:
      - pattern: redirect(...)
      - pattern-not-inside: |
          def safe_redirect(...):
            ...
    message: redirect outside helper
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "def safe_redirect(url):\n    return redirect(url)\n\ndef do_redirect(url):\n    return redirect(url)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 5);
    }

    // ─── metavariable-comparison unit tests ─────────────────────────────────

    #[test]
    fn test_parse_comparison_lt() {
        let (mv, op, lit, flip) = parse_comparison("$X < 10").unwrap();
        assert_eq!(mv, "$X");
        assert_eq!(op, CmpOp::Lt);
        assert!((lit - 10.0).abs() < f64::EPSILON);
        assert!(!flip);
    }

    #[test]
    fn test_parse_comparison_le() {
        let (mv, op, lit, _flip) = parse_comparison("$X <= 5.5").unwrap();
        assert_eq!(op, CmpOp::Le);
        assert!((lit - 5.5).abs() < f64::EPSILON);
        assert_eq!(mv, "$X");
    }

    #[test]
    fn test_parse_comparison_gt() {
        let (_mv, op, lit, _flip) = parse_comparison("$N > 100").unwrap();
        assert_eq!(op, CmpOp::Gt);
        assert!((lit - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_parse_comparison_ge() {
        let (_mv, op, lit, _flip) = parse_comparison("$N >= 0").unwrap();
        assert_eq!(op, CmpOp::Ge);
        assert!((lit - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_parse_comparison_eq() {
        let (mv, op, lit, _flip) = parse_comparison("$VAL == 42").unwrap();
        assert_eq!(op, CmpOp::Eq);
        assert!((lit - 42.0).abs() < f64::EPSILON);
        assert_eq!(mv, "$VAL");
    }

    #[test]
    fn test_parse_comparison_ne() {
        let (_mv, op, lit, _flip) = parse_comparison("$VAL != 0").unwrap();
        assert_eq!(op, CmpOp::Ne);
        assert!((lit - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_parse_comparison_literal_lhs() {
        let (mv, op, lit, flip) = parse_comparison("10 < $X").unwrap();
        assert_eq!(mv, "$X");
        // op is stored as-is from the expression; `flip` indicates literal is LHS
        assert_eq!(op, CmpOp::Lt);
        assert!((lit - 10.0).abs() < f64::EPSILON);
        assert!(flip);
    }

    #[test]
    fn test_parse_comparison_no_metavar_is_err() {
        assert!(parse_comparison("10 < 20").is_err());
    }

    #[test]
    fn test_parse_comparison_no_operator_is_err() {
        assert!(parse_comparison("$X 10").is_err());
    }

    #[test]
    fn test_constraint_matches_numeric_match() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X < 10".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut bindings = HashMap::new();
        bindings.insert("$X".to_string(), "5".to_string());
        assert!(constraint.matches(&bindings));
    }

    #[test]
    fn test_constraint_non_match() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X < 10".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut bindings = HashMap::new();
        bindings.insert("$X".to_string(), "15".to_string());
        assert!(!constraint.matches(&bindings));
    }

    #[test]
    fn test_constraint_non_numeric_binding_no_match() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X < 10".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut bindings = HashMap::new();
        bindings.insert("$X".to_string(), "not_a_number".to_string());
        assert!(!constraint.matches(&bindings));
    }

    #[test]
    fn test_constraint_unbound_metavar_no_match() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X < 10".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let bindings = HashMap::new(); // $X not bound
        assert!(!constraint.matches(&bindings));
    }

    #[test]
    fn test_constraint_float_comparison() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X >= 3.14".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut bindings = HashMap::new();
        bindings.insert("$X".to_string(), "3.14".to_string());
        assert!(constraint.matches(&bindings));
        let mut bindings2 = HashMap::new();
        bindings2.insert("$X".to_string(), "2.0".to_string());
        assert!(!constraint.matches(&bindings2));
    }

    #[test]
    fn test_numeric_suffix_strips_c_float_f_and_preserves_hex() {
        // C float suffix `f`/`F` must be stripped so `2.5f` parses.
        assert_eq!(parse_numeric(&strip_numeric_suffixes("2.5f")), Some(2.5));
        assert_eq!(parse_numeric(&strip_numeric_suffixes("2.5F")), Some(2.5));
        // Integer suffixes still stripped.
        assert_eq!(parse_numeric(&strip_numeric_suffixes("10UL")), Some(10.0));
        // Hex/binary literals must NOT lose their trailing digits to suffix stripping.
        assert_eq!(parse_numeric(&strip_numeric_suffixes("0xFF")), Some(255.0));
        assert_eq!(parse_numeric(&strip_numeric_suffixes("0xff")), Some(255.0));
        assert_eq!(parse_numeric(&strip_numeric_suffixes("0b101")), Some(5.0));
    }

    #[test]
    fn test_constraint_eq_is_exact() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X == 5".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut hit = HashMap::new();
        hit.insert("$X".to_string(), "5".to_string());
        assert!(constraint.matches(&hit));
        let mut miss = HashMap::new();
        miss.insert("$X".to_string(), "6".to_string());
        assert!(!constraint.matches(&miss));
    }

    #[test]
    fn test_constraint_eq_c_float_suffix_binding() {
        // Regression for the `f` suffix bug: a bound C float literal `1.5f`
        // must compare equal to the literal `1.5` rather than being dropped.
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X == 1.5".to_string(),
            base: None,
            strip: None,
        };
        let constraint = MetavariableComparisonConstraint::from_yaml(&clause).unwrap();
        let mut bindings = HashMap::new();
        bindings.insert("$X".to_string(), "1.5f".to_string());
        assert!(constraint.matches(&bindings));
    }

    #[test]
    fn test_constraint_unsupported_base_warn_skip() {
        let clause = SemgrepMetavariableComparisonClause {
            metavariable: Some("$X".to_string()),
            comparison: "$X < 10".to_string(),
            base: Some(16),
            strip: None,
        };
        // Should return Err, not panic
        assert!(MetavariableComparisonConstraint::from_yaml(&clause).is_err());
    }

    #[test]
    fn test_metavariable_comparison_filters_matches_end_to_end() {
        // Full pipeline: parse rule YAML → build matcher → check source
        let yaml = r#"
rules:
  - id: small-arg
    patterns:
      - pattern: foo($X)
      - metavariable-comparison:
          metavariable: $X
          comparison: $X < 10
    message: foo called with small arg
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1);

        // foo(5) → match (5 < 10)
        // foo(20) → no match (20 >= 10)
        // foo(bar) → no match (non-numeric)
        let source = "foo(5)\nfoo(20)\nfoo(bar)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn test_metavariable_comparison_eq_operator_end_to_end() {
        let yaml = r#"
rules:
  - id: exact-zero
    patterns:
      - pattern: check($N)
      - metavariable-comparison:
          metavariable: $N
          comparison: $N == 0
    message: called with zero
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "check(0)\ncheck(1)\ncheck(2)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].line, 1);
    }

    /// metavariable-pattern: the binding for $FUNC must itself match a nested
    /// AST sub-pattern.
    #[test]
    fn test_metavariable_pattern_match() {
        // $FUNC must itself be a call matching `dangerous(...)`.
        // Source line 1 calls eval(dangerous(x)) — $FUNC captures dangerous(x)
        // which matches `dangerous(...)`.
        // Source line 2 calls eval(safe(x)) — $FUNC captures safe(x)
        // which does NOT match `dangerous(...)`.
        let yaml = r#"
rules:
  - id: mvp-match
    patterns:
      - pattern: eval($FUNC)
      - metavariable-pattern:
          metavariable: $FUNC
          pattern: dangerous(...)
    message: dangerous arg in eval
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "eval(dangerous(x))\neval(safe(x))\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(findings.len(), 1, "expected exactly one finding");
        assert_eq!(findings[0].line, 1);
    }

    /// Non-match case: binding exists but the sub-pattern does not match it.
    #[test]
    fn test_metavariable_pattern_no_match() {
        let yaml = r#"
rules:
  - id: mvp-no-match
    patterns:
      - pattern: eval($FUNC)
      - metavariable-pattern:
          metavariable: $FUNC
          pattern: dangerous(...)
    message: dangerous arg
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "eval(safe(x))\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(
            findings.len(),
            0,
            "expected no findings when sub-pattern does not match"
        );
    }

    /// pattern-regex nested form: the bound text is matched via regex.
    #[test]
    fn test_metavariable_pattern_regex_nested() {
        let yaml = r#"
rules:
  - id: mvp-regex
    patterns:
      - pattern: '"..." + $VAR'
      - metavariable-pattern:
          metavariable: $VAR
          pattern-regex: '^user_'
    message: user-prefixed var in concat
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "q = \"SELECT \" + user_input\nq2 = \"SELECT \" + data\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected exactly one finding for user_ variable"
        );
        assert_eq!(findings[0].line, 1);
    }

    /// Warn-skip: an unsupported nested shape should warn and skip the
    /// constraint without crashing, leaving other clauses active.
    #[test]
    fn test_metavariable_pattern_unsupported_nested_shape_warn_skip() {
        // metavariable-pattern clause has neither pattern, pattern-regex, nor
        // pattern-either — it has no recognised keys at all. The constraint
        // should be silently dropped and the positive pattern `eval(...)` still
        // fires on the source (no constraint to filter with).
        let yaml = r#"
rules:
  - id: mvp-warn-skip
    patterns:
      - pattern: eval(...)
      - metavariable-pattern:
          metavariable: $FUNC
    message: eval usage (constraint skipped)
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        // Loading must succeed (no panic, no Err).
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1, "rule should still load after warn-skip");

        // The positive pattern fires; the skipped constraint is absent.
        let source = "eval(x)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        // Without the constraint, the positive `eval(...)` still matches.
        assert!(!findings.is_empty(), "positive pattern should still fire");
    }

    // ─── focus-metavariable tests ────────────────────────────────────────────

    /// focus-metavariable: the reported finding range must point at $VAR (the
    /// argument), NOT at the outer call expression.
    ///
    /// Source: `foo(bar)\n`
    ///   - full match `foo(bar)` is at line 1, col 1..8
    ///   - argument `bar` is at line 1, col 5..7 (1-based)
    ///
    /// With focus-metavariable: $ARG, the finding should have line=1, col=5.
    #[test]
    fn test_focus_metavariable_range_override() {
        let yaml = r#"
rules:
  - id: focus-test
    patterns:
      - pattern: foo($ARG)
      - focus-metavariable: $ARG
    message: focus on arg
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        // "foo(bar)\n" — `bar` starts at byte 4 (0-based), which is col 5 (1-based)
        let source = "foo(bar)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1, "expected one finding");

        // The full match `foo(bar)` is at line 1, column 1.
        // With focus-metavariable, it should instead point at `bar` (col 5).
        assert_eq!(findings[0].line, 1, "finding should be on line 1");
        assert_ne!(
            findings[0].column, 1,
            "column should NOT be 1 (that's the full match start); focus-metavariable must override it"
        );
        // `bar` is the 5th character on line 1 (1-based).
        assert_eq!(
            findings[0].column, 5,
            "focused metavariable $ARG should start at column 5"
        );
    }

    /// focus-metavariable with a list: accept `focus-metavariable: [$ARG]`.
    #[test]
    fn test_focus_metavariable_list_syntax() {
        let yaml = r#"
rules:
  - id: focus-list-test
    patterns:
      - pattern: foo($ARG)
      - focus-metavariable: [$ARG]
    message: focus on arg
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "foo(bar)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1, "expected one finding");
        assert_eq!(findings[0].column, 5, "$ARG should start at column 5");
    }

    /// focus-metavariable fallback: when the named metavar is not bound in a
    /// match (won't happen in a well-formed rule, but verify no crash/drop).
    #[test]
    fn test_focus_metavariable_unbound_fallback() {
        // This rule focuses on $MISSING which is never bound by the pattern.
        // The finding must still be emitted at the full match range.
        let yaml = r#"
rules:
  - id: focus-fallback
    patterns:
      - pattern: eval(...)
      - focus-metavariable: $MISSING
    message: fallback test
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "eval(user_input)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        // Finding must still be emitted (no drop on missing metavar).
        assert_eq!(findings.len(), 1, "finding must not be dropped");
        // Falls back to full match at line 1, column 1
        assert_eq!(findings[0].line, 1);
        assert_eq!(
            findings[0].column, 1,
            "should fall back to full match column"
        );
    }

    // ─── fix: autofix template tests ────────────────────────────────────────

    /// (a) A rule with `fix:` referencing a metavar produces a finding whose
    /// `fix_suggestion` has the metavar substituted with the bound value.
    #[test]
    fn test_fix_template_substitutes_bound_metavar() {
        let yaml = r#"
rules:
  - id: use-safe-func
    pattern: unsafe_call($X)
    fix: safe_call($X)
    message: Use safe_call instead
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "unsafe_call(user_data)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1);
        assert_eq!(
            findings[0].fix_suggestion.as_deref(),
            Some("safe_call(user_data)"),
            "metavar $X should be substituted with the bound text 'user_data'"
        );
    }

    /// (b) A rule without `fix:` yields `fix_suggestion: None`.
    #[test]
    fn test_no_fix_key_yields_no_fix_suggestion() {
        let yaml = r#"
rules:
  - id: test-eval-no-fix
    pattern: eval(...)
    message: Do not use eval
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "eval(user_input)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1);
        assert!(
            findings[0].fix_suggestion.is_none(),
            "fix_suggestion should be None when no fix: key is present"
        );
    }

    /// (c) An unbound metavar token in the template is left literal — no panic.
    #[test]
    fn test_fix_template_unbound_metavar_left_literal() {
        let yaml = r#"
rules:
  - id: fix-unbound
    pattern: eval(...)
    fix: safe_eval($UNBOUND)
    message: Use safe_eval
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "eval(x)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1);
        // $UNBOUND is not bound by the pattern (which uses ..., no named metavar)
        // so the token should remain as-is in the suggestion.
        assert_eq!(
            findings[0].fix_suggestion.as_deref(),
            Some("safe_eval($UNBOUND)"),
            "unbound metavar token should be left literal, not panic"
        );
    }

    /// (a2) fix: with multiple metavars — each is substituted independently.
    #[test]
    fn test_fix_template_multiple_metavars() {
        let yaml = r#"
rules:
  - id: fix-multi
    pattern: old($A, $B)
    fix: new($B, $A)
    message: swap args
    severity: INFO
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "old(foo, bar)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1);
        assert_eq!(
            findings[0].fix_suggestion.as_deref(),
            Some("new(bar, foo)"),
            "both metavars should be substituted correctly"
        );
    }

    // ─── metavariable-analysis / entropy unit tests ──────────────────────────

    /// `shannon_entropy` sanity checks: high-entropy token vs low-entropy word.
    #[test]
    fn test_shannon_entropy_values() {
        // "Zq7Z9kW3pL8xT2nR4dB6m" — random high-entropy token
        let high = shannon_entropy("Zq7Z9kW3pL8xT2nR4dB6m");
        assert!(
            high >= 3.5,
            "expected entropy >= 3.5 for high-entropy token, got {high}"
        );

        // "hello" — low entropy
        let low = shannon_entropy("hello");
        assert!(low < 3.0, "expected entropy < 3.0 for 'hello', got {low}");

        // empty string
        assert_eq!(shannon_entropy(""), 0.0);
    }

    /// entropy constraint: matches a high-entropy token.
    #[test]
    fn test_metavariable_analysis_entropy_matches_high_entropy() {
        let clause = SemgrepMetavariableAnalysisClause {
            metavariable: "$TOKEN".to_string(),
            analyzer: "entropy".to_string(),
        };
        let constraint = MetavariableAnalysisConstraint::from_yaml(&clause)
            .expect("entropy analyzer should build successfully");

        let mut bindings = HashMap::new();
        // base64-ish token with high entropy
        bindings.insert(
            "$TOKEN".to_string(),
            "aB3xQz9mKp2LwYv5NtRsUhJdEfCgOiV7".to_string(),
        );
        assert!(
            constraint.matches(&bindings),
            "entropy constraint must match a high-entropy token"
        );
    }

    /// entropy constraint: does NOT match a low-entropy word.
    #[test]
    fn test_metavariable_analysis_entropy_no_match_low_entropy() {
        let clause = SemgrepMetavariableAnalysisClause {
            metavariable: "$TOKEN".to_string(),
            analyzer: "entropy".to_string(),
        };
        let constraint = MetavariableAnalysisConstraint::from_yaml(&clause).unwrap();

        let mut bindings = HashMap::new();
        bindings.insert("$TOKEN".to_string(), "password".to_string());
        assert!(
            !constraint.matches(&bindings),
            "entropy constraint must NOT match 'password'"
        );
    }

    /// entropy constraint: unbound metavar → no match (no panic).
    #[test]
    fn test_metavariable_analysis_entropy_unbound_metavar_no_match() {
        let clause = SemgrepMetavariableAnalysisClause {
            metavariable: "$TOKEN".to_string(),
            analyzer: "entropy".to_string(),
        };
        let constraint = MetavariableAnalysisConstraint::from_yaml(&clause).unwrap();

        let bindings = HashMap::new(); // $TOKEN not bound
        assert!(
            !constraint.matches(&bindings),
            "unbound metavar must return false (no panic)"
        );
    }

    /// redos analyzer: warn-skips without crashing (from_yaml returns None).
    #[test]
    fn test_metavariable_analysis_redos_warn_skips() {
        let clause = SemgrepMetavariableAnalysisClause {
            metavariable: "$RE".to_string(),
            analyzer: "redos".to_string(),
        };
        // Must return None (warn-skip), not panic or Err.
        let result = MetavariableAnalysisConstraint::from_yaml(&clause);
        assert!(
            result.is_none(),
            "redos analyzer must warn-skip (return None)"
        );
    }

    /// Unknown analyzer: warn-skips without crashing.
    #[test]
    fn test_metavariable_analysis_unknown_analyzer_warn_skips() {
        let clause = SemgrepMetavariableAnalysisClause {
            metavariable: "$X".to_string(),
            analyzer: "future-magic-analyzer".to_string(),
        };
        let result = MetavariableAnalysisConstraint::from_yaml(&clause);
        assert!(
            result.is_none(),
            "unknown analyzer must warn-skip (return None)"
        );
    }

    /// End-to-end: a rule with metavariable-analysis entropy fires on a
    /// high-entropy bound value and is suppressed on a low-entropy value.
    #[test]
    fn test_metavariable_analysis_entropy_end_to_end() {
        let yaml = r#"
rules:
  - id: hardcoded-secret-entropy
    patterns:
      - pattern: 'token = "$VALUE"'
      - metavariable-analysis:
          metavariable: $VALUE
          analyzer: entropy
    message: Hardcoded high-entropy token detected
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1, "rule must load successfully");

        // High-entropy token: should fire
        let high_entropy_source = r#"token = "aB3xQz9mKp2LwYv5NtRsUhJdEfCgOiV7"
"#;
        let tree = parse_file(high_entropy_source, Language::Python).unwrap();
        let findings = rules[0].check(high_entropy_source, &tree);
        assert_eq!(
            findings.len(),
            1,
            "entropy rule must fire on high-entropy token"
        );

        // Low-entropy token: should NOT fire
        let low_entropy_source = r#"token = "password"
"#;
        let tree2 = parse_file(low_entropy_source, Language::Python).unwrap();
        let findings2 = rules[0].check(low_entropy_source, &tree2);
        assert_eq!(
            findings2.len(),
            0,
            "entropy rule must NOT fire on low-entropy word"
        );
    }

    /// End-to-end: a rule with redos analyzer must load (warn-skip) and the
    /// positive pattern still fires (constraint is absent, not blocking).
    #[test]
    fn test_metavariable_analysis_redos_warn_skip_end_to_end() {
        let yaml = r#"
rules:
  - id: redos-test
    patterns:
      - pattern: 'regex = "$PATTERN"'
      - metavariable-analysis:
          metavariable: $PATTERN
          analyzer: redos
    message: Possible ReDoS pattern
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        // Rule must load without error; warn-skip is printed to stderr.
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert_eq!(rules.len(), 1, "rule must load after warn-skip");

        // With redos constraint dropped, the positive pattern fires unconstrained.
        let source = r#"regex = "(a+)+"
"#;
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        // The positive pattern still matches; no crash.
        assert_eq!(
            findings.len(),
            1,
            "positive pattern must still fire when redos constraint is warn-skipped"
        );
    }

    /// focus-metavariable: two-line source — confirm the focused metavar is on
    /// line 2 when the match is on line 2.
    #[test]
    fn test_focus_metavariable_multiline_source() {
        let yaml = r#"
rules:
  - id: focus-multiline
    patterns:
      - pattern: sink($X)
      - focus-metavariable: $X
    message: focus on X
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        // Only line 2 has a match.
        let source = "safe(a)\nsink(b)\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);

        assert_eq!(findings.len(), 1, "expected one finding on line 2");
        assert_eq!(
            findings[0].line, 2,
            "focused metavar $X should be on line 2"
        );
        // `b` is the 6th character on line 2 in "sink(b)"
        assert_eq!(findings[0].column, 6, "$X (`b`) should be at column 6");
    }

    // ── languages: [regex] ────────────────────────────────────────────────────

    /// (a) A `languages: [regex]` rule with `pattern-regex` loads (produces rule
    /// instances) and FIRES on a file whose text matches.
    #[test]
    fn regex_lang_rule_loads_and_fires_on_matching_text() {
        let yaml = r#"
rules:
  - id: test/detect-token
    pattern-regex: "MYTOKEN[0-9]{4}"
    languages: [regex]
    message: Token detected
    severity: ERROR
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        // Fan-out produces one instance per detectable language.
        assert!(
            !rules.is_empty(),
            "regex-mode rule should produce at least one rule instance"
        );

        // All instances should have the correct id, severity, and language.
        for rule in &rules {
            assert_eq!(rule.id(), "semgrep/test/detect-token");
            assert_eq!(rule.severity(), Severity::Critical);
        }

        // Pick any instance and run it against matching text.
        let source = "access_token = \"MYTOKEN1234\"\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(
            findings.len(),
            1,
            "expected exactly one finding for matching text"
        );
        assert_eq!(findings[0].line, 1);
    }

    /// (b) The same rule does NOT fire on non-matching text.
    #[test]
    fn regex_lang_rule_does_not_fire_on_non_matching_text() {
        let yaml = r#"
rules:
  - id: test/detect-token
    pattern-regex: "MYTOKEN[0-9]{4}"
    languages: [regex]
    message: Token detected
    severity: ERROR
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();

        let source = "access_token = \"NOT_A_TOKEN\"\n";
        let tree = parse_file(source, Language::Python).unwrap();
        let findings = rules[0].check(source, &tree);
        assert!(
            findings.is_empty(),
            "regex-mode rule must not fire on non-matching text"
        );
    }

    /// (c) `paths.include` / `paths.exclude` respected by the regex-mode rule.
    #[test]
    fn regex_lang_rule_respects_paths_filter() {
        let yaml = r#"
rules:
  - id: test/jsp-scriptlet
    pattern-regex: "<%[^@]"
    languages: [regex]
    message: JSP scriptlet detected
    severity: WARNING
    paths:
      include:
        - "*.jsp"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert!(!rules.is_empty(), "should produce at least one rule");

        // Should apply to .jsp files.
        assert!(
            rules[0].applies_to_path(std::path::Path::new("view.jsp")),
            "rule should apply to .jsp files"
        );
        // Should NOT apply to .py files.
        assert!(
            !rules[0].applies_to_path(std::path::Path::new("main.py")),
            "rule must not apply to .py files when paths.include = [*.jsp]"
        );
    }

    /// (d) A `languages: [regex]` rule with only an AST `pattern:` (no
    /// `pattern-regex`) should warn-skip (produce zero rule instances).
    #[test]
    fn regex_lang_rule_with_only_ast_pattern_warns_and_skips() {
        let yaml = r#"
rules:
  - id: test/ast-only-in-regex-mode
    pattern: eval(...)
    languages: [regex]
    message: This should be skipped
    severity: ERROR
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert!(
            rules.is_empty(),
            "regex-mode rule with only an AST pattern must produce zero rule instances"
        );
    }

    /// Regex-mode rule with `patterns:` block (pattern-regex + pattern-not-regex)
    /// loads and correctly applies negation.
    #[test]
    fn regex_lang_rule_patterns_block_with_negation() {
        let yaml = r#"
rules:
  - id: test/detect-artifactory-token
    patterns:
      - pattern-regex: "\\bAKC[a-zA-Z0-9]{10,}"
      - pattern-not-regex: "sha(128|256|512)"
    languages: [regex]
    message: Artifactory token detected
    severity: ERROR
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).unwrap();
        assert!(!rules.is_empty(), "should produce rule instances");

        let tree = parse_file("x = 1\n", Language::Python).unwrap();

        // Matching text without the excluded pattern — should fire.
        let matching = "token = \"AKCp1234567890abcdef\"\n";
        let findings = rules[0].check(matching, &tree);
        assert_eq!(
            findings.len(),
            1,
            "should fire on text matching pattern-regex"
        );

        // Text matching the negative pattern — should NOT fire.
        let negated = "hash = \"sha256_AKCp1234567890abcdef\"\n";
        let findings = rules[0].check(negated, &tree);
        assert!(
            findings.is_empty(),
            "should not fire when pattern-not-regex also matches"
        );
    }

    // ── Regression tests for "loader rejected (other)" fixes ────────────────

    /// Fix 1: `severity: MEDIUM` must load without error.
    ///
    /// Regression for rules such as `supply-chain/audit/go-audit-...` that
    /// use `MEDIUM` as their severity value.  Previously the serde deserialiser
    /// rejected the value because the enum only had ERROR/WARNING/INFO.
    #[test]
    fn test_severity_medium_loads() {
        let yaml = r#"
rules:
  - id: medium-sev-rule
    pattern: foo()
    message: medium severity rule
    severity: MEDIUM
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).expect("MEDIUM severity rule must load");
        assert_eq!(rules.len(), 1);
    }

    /// Fix 2: `metavariable-comparison:` without a `metavariable:` key must
    /// warn-skip the comparison constraint and still load the rule.
    ///
    /// Regression for rules such as `python/sql-injection-...` that use
    /// `comparison: str($F1) == str($F2)` (two metavar operands, no single
    /// bound metavar key).
    #[test]
    fn test_metavariable_comparison_without_metavariable_key_loads_rule() {
        let yaml = r#"
rules:
  - id: cmp-no-metavar-key
    patterns:
      - pattern: foo($F1, $F2)
      - metavariable-comparison:
          comparison: $F1 > $F2
    message: comparison without metavariable key
    severity: WARNING
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).expect(
            "rule with metavariable-comparison missing `metavariable:` key must still load",
        );
        assert_eq!(rules.len(), 1);
    }

    /// Fix 3: `metavariable-regex:` with a lookahead pattern must warn-skip
    /// the constraint and still load the rule.
    ///
    /// Regression for rules such as `javascript/hardcoded-...` that use
    /// `(?!...)` lookahead assertions in their `metavariable-regex` value.
    /// The Rust `regex` crate does not support PCRE lookaheads; previously
    /// this caused the entire rule to fail to load.
    #[test]
    fn test_metavariable_regex_with_lookahead_loads_rule() {
        let yaml = r#"
rules:
  - id: mv-regex-lookahead
    patterns:
      - pattern: |
          var $X = "...";
      - metavariable-regex:
          metavariable: $X
          regex: '(?!localhost).*'
    message: hardcoded non-localhost value
    severity: WARNING
    languages: [javascript]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("rule with lookahead in metavariable-regex must still load");
        assert_eq!(rules.len(), 1);
    }

    /// Fix 4: `\Z` in a `pattern-regex` value must compile successfully.
    ///
    /// Regression for the PHP `assert-use-audit` rule which uses `\Z` (Python
    /// end-of-string anchor) in its primary `pattern-regex`.  The Rust `regex`
    /// crate uses `$` for the same purpose; we normalise `\Z` → `$` before
    /// compilation.
    #[test]
    fn test_pattern_regex_backslash_z_anchor_loads() {
        // `\Z` normalised to `$` — the rule must load without error.
        let yaml = r#"
rules:
  - id: pattern-regex-z-anchor
    pattern-regex: 'assert\s*\(\s*\$\w+\s*\)\s*\Z'
    message: assert usage
    severity: WARNING
    languages: [php]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("pattern-regex with \\Z anchor must load after normalisation");
        assert_eq!(rules.len(), 1);
    }

    // ─── Dockerfile language tests ────────────────────────────────────────────

    /// A `languages: [dockerfile]` rule loads without error.
    #[test]
    fn test_dockerfile_language_rule_loads() {
        let yaml = r#"
rules:
  - id: dockerfile-no-latest
    pattern-regex: ':latest'
    message: Avoid using the latest tag in Dockerfile FROM instructions
    severity: WARNING
    languages: [dockerfile]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("dockerfile language rule must load without error");
        assert_eq!(rules.len(), 1, "expected one rule for dockerfile language");
    }

    /// A `languages: [docker]` alias also loads.
    #[test]
    fn test_docker_language_alias_loads() {
        let yaml = r#"
rules:
  - id: docker-root-user
    pattern-regex: 'USER\s+root'
    message: Container should not run as root
    severity: ERROR
    languages: [docker]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("docker language alias must load without error");
        assert!(
            !rules.is_empty(),
            "docker alias should produce rule instances"
        );
    }

    /// A `languages: [dockerfile]` `pattern-regex` rule matches inside a sample Dockerfile.
    #[test]
    fn test_dockerfile_pattern_regex_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: dockerfile-latest-tag
    pattern-regex: ':latest'
    message: Avoid :latest tag
    severity: WARNING
    languages: [dockerfile]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).expect("rule must load");
        assert_eq!(rules.len(), 1);

        let source = "FROM ubuntu:latest\nRUN apt-get update\nCMD [\"/bin/bash\"]\n";
        let tree = parse_path(source, Language::Dockerfile, Path::new("Dockerfile"))
            .expect("Dockerfile must parse");
        assert!(
            !tree.root_node().has_error(),
            "Dockerfile parse must be error-free"
        );

        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern-regex ':latest' must match 'ubuntu:latest' in Dockerfile"
        );
    }

    /// A `languages: [bash]` rule loads successfully.
    #[test]
    fn test_bash_language_loads() {
        let yaml = r#"
rules:
  - id: bash-eval-call
    pattern: eval $X
    message: Avoid eval in bash
    severity: WARNING
    languages: [bash]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("bash language rule must load without error");
        assert_eq!(rules.len(), 1, "expected one rule for bash language");
    }

    /// A `languages: [ocaml]` rule loads successfully.
    #[test]
    fn test_ocaml_language_loads() {
        let yaml = r#"
rules:
  - id: ocaml-pattern
    pattern-regex: 'Sys\.command'
    message: Avoid Sys.command
    severity: WARNING
    languages: [ocaml]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("ocaml language rule must load without error");
        assert!(!rules.is_empty(), "expected rules for ocaml language");
    }

    /// A `languages: [apex]` `pattern:` rule loads and matches inside Apex source.
    #[test]
    fn test_apex_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: apex-debug-call
    pattern: System.debug(...)
    message: Avoid System.debug
    severity: WARNING
    languages: [apex]
"#;
        let rules = parse_semgrep_str(yaml, "apex.yml")
            .expect("apex language rule must load without error");
        assert_eq!(rules.len(), 1, "expected one rule for apex language");

        let source = "public class A {\n  void f() {\n    System.debug('x');\n  }\n}\n";
        let tree = parse_path(source, Language::Apex, Path::new("A.cls")).expect("Apex must parse");
        assert!(
            !tree.root_node().has_error(),
            "Apex parse must be error-free"
        );
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern System.debug(...) must match in Apex"
        );
    }

    /// A `languages: [clojure]` `pattern:` rule loads and matches inside Clojure source.
    #[test]
    fn test_clojure_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: clojure-eval-call
    pattern: (eval $X)
    message: Avoid eval
    severity: WARNING
    languages: [clojure]
"#;
        let rules = parse_semgrep_str(yaml, "clojure.yml")
            .expect("clojure language rule must load without error");
        assert_eq!(rules.len(), 1, "expected one rule for clojure language");

        let source = "(defn f [x]\n  (eval x))\n";
        let tree = parse_path(source, Language::Clojure, Path::new("core.clj"))
            .expect("Clojure must parse");
        assert!(
            !tree.root_node().has_error(),
            "Clojure parse must be error-free"
        );
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern (eval ...) must match in Clojure"
        );
    }

    /// A `languages: [html]` `pattern-regex` rule loads and matches inside HTML source.
    #[test]
    fn test_html_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: html-inline-onclick
    pattern-regex: 'onclick='
    message: Avoid inline event handlers
    severity: WARNING
    languages: [html]
"#;
        let rules = parse_semgrep_str(yaml, "html.yml").expect("html language rule must load");
        assert_eq!(rules.len(), 1, "expected one rule for html language");

        let source =
            "<html>\n  <body>\n    <button onclick=\"go()\">x</button>\n  </body>\n</html>\n";
        let tree =
            parse_path(source, Language::Html, Path::new("index.html")).expect("HTML must parse");
        assert!(
            !tree.root_node().has_error(),
            "HTML parse must be error-free"
        );
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern-regex onclick= must match in HTML"
        );
    }

    /// A `languages: [xml]` `pattern-regex` rule loads and matches inside XML source.
    #[test]
    fn test_xml_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: xml-doctype
    pattern-regex: '<!DOCTYPE'
    message: Avoid DOCTYPE declarations
    severity: WARNING
    languages: [xml]
"#;
        let rules = parse_semgrep_str(yaml, "xml.yml").expect("xml language rule must load");
        assert_eq!(rules.len(), 1, "expected one rule for xml language");

        let source =
            "<?xml version=\"1.0\"?>\n<!DOCTYPE root>\n<root>\n  <child>text</child>\n</root>\n";
        let tree =
            parse_path(source, Language::Xml, Path::new("data.xml")).expect("XML must parse");
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern-regex <!DOCTYPE must match in XML"
        );
    }

    /// A `languages: [dart]` search rule loads and matches inside Dart source.
    #[test]
    fn test_dart_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: dart-print-call
    pattern-regex: 'print\('
    message: Avoid print
    severity: WARNING
    languages: [dart]
"#;
        let rules = parse_semgrep_str(yaml, "dart.yml").expect("dart language rule must load");
        assert_eq!(rules.len(), 1, "expected one rule for dart language");

        let source = "void main() {\n  print('hello');\n}\n";
        let tree =
            parse_path(source, Language::Dart, Path::new("main.dart")).expect("Dart must parse");
        assert!(
            !tree.root_node().has_error(),
            "Dart parse must be error-free"
        );
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern-regex print\\( must match in Dart"
        );
    }

    /// A `languages: [haskell]` `pattern-regex` rule loads and matches inside Haskell source.
    #[test]
    fn test_haskell_pattern_loads_and_matches() {
        use crate::engine::parser::parse_path;
        use std::path::Path;

        let yaml = r#"
rules:
  - id: haskell-foreign-import
    pattern-regex: '\bforeign\s+import\b'
    message: Review Haskell FFI boundary
    severity: WARNING
    languages: [haskell]
"#;
        let rules =
            parse_semgrep_str(yaml, "haskell.yml").expect("haskell language rule must load");
        assert_eq!(rules.len(), 1, "expected one rule for haskell language");

        let source = "module Bindings where\nforeign import ccall \"foo\" c_foo :: IO ()\n";
        let tree = parse_path(source, Language::Haskell, Path::new("Bindings.hs"))
            .expect("Haskell must parse");
        assert!(
            !tree.root_node().has_error(),
            "Haskell parse must be error-free"
        );
        let findings = rules[0].check(source, &tree);
        assert!(
            !findings.is_empty(),
            "pattern-regex foreign import must match in Haskell"
        );
    }

    /// A `languages: [scala]` rule loads successfully.
    #[test]
    fn test_scala_language_loads() {
        let yaml = r#"
rules:
  - id: scala-pattern
    pattern-regex: 'Runtime\.getRuntime\(\)'
    message: Avoid Runtime.getRuntime
    severity: WARNING
    languages: [scala]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("scala language rule must load without error");
        assert!(!rules.is_empty(), "expected rules for scala language");
    }

    /// A `languages: [elixir]` rule loads successfully.
    #[test]
    fn test_elixir_language_loads() {
        let yaml = r#"
rules:
  - id: elixir-pattern
    pattern: System.cmd($CMD, ...)
    message: Avoid System.cmd with untrusted input
    severity: WARNING
    languages: [elixir]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("elixir language rule must load without error");
        assert_eq!(rules.len(), 1, "expected one rule for elixir language");
    }

    /// A `languages: [json]` rule loads successfully.
    #[test]
    fn test_json_language_loads() {
        let yaml = r#"
rules:
  - id: json-pattern
    pattern-regex: '"password"\s*:\s*"[^"]+"'
    message: Hardcoded password in JSON
    severity: ERROR
    languages: [json]
"#;
        let f = make_yaml(yaml);
        let rules =
            parse_semgrep_file(f.path()).expect("json language rule must load without error");
        assert!(!rules.is_empty(), "expected rules for json language");
    }

    // ─── Regression tests for the PR #fix-loader-rejected-2 batch ────────────
    // Each test names the specific registry rule (or shape) that was previously
    // rejected and now must load.

    /// Bare `{{` in a `pattern-regex` (Flask/Django template rules).
    ///
    /// Regression for `template-unescaped-with-safe`, `template-autoescape-off`,
    /// `template-var-unescaped-with-safeseq`, `debug-template-tag`, etc.
    /// The Rust `regex` crate rejects bare `{` not forming a valid quantifier;
    /// we now escape them in `compile_regex` via `escape_bare_braces`.
    #[test]
    fn test_bare_double_brace_in_pattern_regex_loads() {
        let yaml = r#"
rules:
  - id: test/flask-template-safe-filter
    pattern-regex: '{{.*?\|\s*safe(\s*}})?'
    message: Jinja2 template uses |safe filter
    severity: WARNING
    languages: [regex]
    paths:
      include:
        - "*.html"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("pattern-regex with bare {{ must load after brace normalisation");
        assert!(
            !rules.is_empty(),
            "bare {{ pattern-regex rule must produce at least one rule instance"
        );
    }

    /// Bare `{%` in a `pattern-regex` (Flask autoescape-off rule).
    ///
    /// Regression for `template-autoescape-off` (flask, django).
    #[test]
    fn test_bare_brace_percent_in_pattern_regex_loads() {
        let yaml = r#"
rules:
  - id: test/flask-autoescape-off
    pattern-regex: '{%\s*autoescape\s+false\s*%}'
    message: Flask autoescape disabled
    severity: WARNING
    languages: [regex]
    paths:
      include:
        - "*.html"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("pattern-regex with bare {% must load after brace normalisation");
        assert!(
            !rules.is_empty(),
            "bare {{%}} pattern-regex rule must produce at least one rule instance"
        );
    }

    /// `{` followed by `[` (not a digit) in a `pattern-regex` (slow-pattern-general-func).
    ///
    /// Regression for `slow-pattern-general-func` (yaml language).
    #[test]
    fn test_bare_brace_before_bracket_in_pattern_regex_loads() {
        // `{[\s\n]*` — the `{` is not a valid quantifier start here.
        let yaml = r#"
rules:
  - id: test/slow-pattern
    pattern-regex: 'function[^{]*{[\s\n]*\.\.\.[\s\n]*}'
    message: Slow pattern
    severity: WARNING
    languages: [yaml]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("pattern-regex with bare { before [ must load after brace normalisation");
        assert!(
            !rules.is_empty(),
            "rule must produce at least one instance after brace normalisation"
        );
    }

    /// `!{.*?}` in a `pattern-either` entry (Pug explicit-unescape rule).
    ///
    /// Regression for `template-explicit-unescape` (pug).  The rule uses two
    /// `pattern-either` entries; the `!{.*?}` entry previously caused the
    /// whole rule to fail.  After the brace-normalisation fix the entry loads
    /// and the rule produces matchers for the remaining entry too.
    #[test]
    fn test_bare_brace_in_pattern_either_entry_loads() {
        let yaml = r#"
rules:
  - id: test/pug-unescape
    pattern-either:
      - pattern-regex: '\w.*(!=)[^=].*'
      - pattern-regex: '!{.*?}'
    message: Pug explicit unescape
    severity: WARNING
    languages: [regex]
    paths:
      include:
        - "*.pug"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("pattern-either with bare { entry must load after brace normalisation");
        assert!(
            !rules.is_empty(),
            "rule with pattern-either including bare-brace regex must load"
        );
    }

    /// Lookahead in a `pattern-either` entry must be gracefully skipped.
    ///
    /// Regression for `aws-lambda-environment-credentials` (hcl): its
    /// `pattern-either:` block mixes `pattern-inside:` entries (which work)
    /// with `pattern-regex:` entries that use lookbehind (which Rust's
    /// `regex` crate rejects).  The bad `pattern-regex` entries should be
    /// warn-skipped; the two `pattern-inside` entries should still compile,
    /// and the rule should load.
    #[test]
    fn test_lookahead_in_pattern_either_entry_is_gracefully_skipped() {
        let yaml = r#"
rules:
  - id: test/aws-credential-detection
    patterns:
      - pattern-inside: |
          resource "$ANY" $ANYTHING {
            ...
          }
      - pattern-either:
          - pattern-inside: 'AWS_ACCESS_KEY_ID = "$Y"'
          - pattern-regex: '(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])'
          - pattern-inside: 'AWS_SECRET_ACCESS_KEY = "$Y"'
      - focus-metavariable: $Y
    message: Hardcoded AWS credential
    severity: ERROR
    languages: [hcl]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("rule with lookahead in pattern-either must load with the bad entry skipped");
        // The rule loads (the two pattern-inside entries survive); it may not
        // match the exact HCL shape but it must not be rejected entirely.
        assert!(
            !rules.is_empty(),
            "rule must produce at least one rule instance"
        );
    }

    /// `pattern-not-regex` with a backreference must be gracefully skipped.
    ///
    /// Regression for `detected-artifactory-password`: its `patterns:` block
    /// has valid `pattern-regex` positives but a `pattern-not-regex` using
    /// `\1` (backreference).  The bad negative should be warn-skipped and the
    /// rule should load with the remaining patterns intact.
    #[test]
    fn test_backreference_in_pattern_not_regex_is_gracefully_skipped() {
        let yaml = r#"
rules:
  - id: test/artifactory-password
    patterns:
      - pattern-regex: '\bAP[0-9A-F][a-zA-Z0-9]{8,}'
      - pattern-regex: '(?i)artifactory'
      - pattern-not-regex: '(\w|\.|\*)\1{4}'
    languages: [regex]
    message: Artifactory token detected
    severity: ERROR
    paths:
      exclude:
        - "*.svg"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).expect(
            "rule with backreference in pattern-not-regex must load with that entry skipped",
        );
        assert!(
            !rules.is_empty(),
            "rule must produce at least one rule instance"
        );
    }

    /// `pattern-not-inside:` with a nested `patterns:` block must load.
    ///
    /// Regression for `last-user-is-root` (dockerfile): the rule uses
    /// `pattern-not-inside:` with a map value (`patterns: [...]`) instead of
    /// a plain string.  Previously the YAML deserializer rejected this with
    /// "invalid type: map, expected a string".
    ///
    /// After the fix, the outermost `pattern:` string is extracted from the
    /// nested block and used as the `not_inside` constraint; the inner
    /// `metavariable-pattern:` sub-constraint is gracefully dropped.
    #[test]
    fn test_pattern_not_inside_nested_block_loads() {
        let yaml = r#"
rules:
  - id: test/last-user-is-root
    patterns:
      - pattern: USER root
      - pattern-not-inside:
          patterns:
            - pattern: |
                USER root
                ...
                USER $X
            - metavariable-pattern:
                metavariable: $X
                patterns:
                  - pattern-not: root
    message: Last container user is root
    severity: ERROR
    languages: [dockerfile]
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("rule with nested patterns: block inside pattern-not-inside: must load");
        assert!(
            !rules.is_empty(),
            "rule must produce at least one rule instance"
        );
    }

    /// `{{{` triple brace in a `pattern-either` (Mustache explicit-unescape).
    ///
    /// Regression for `template-explicit-unescape` (mustache): its second
    /// `pattern-either` entry `{{[\s]*&.*}}` should load after brace
    /// normalisation.  The first entry (which also has a lookahead) is
    /// gracefully skipped; the rule still loads from the second entry.
    #[test]
    fn test_double_brace_ampersand_pattern_in_pattern_either_loads() {
        let yaml = r#"
rules:
  - id: test/mustache-unescape
    pattern-either:
      - pattern-regex: '{{{((?!include).)*?}}}'
      - pattern-regex: '{{[\s]*&.*}}'
    message: Mustache explicit unescape
    severity: WARNING
    languages: [regex]
    paths:
      include:
        - "*.mustache"
        - "*.hbs"
        - "*.html"
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path()).expect(
            "mustache pattern-either with brace+lookahead entry must load (second entry survives)",
        );
        assert!(
            !rules.is_empty(),
            "rule must produce at least one rule instance from the second pattern-either entry"
        );
    }

    /// `brace_normalisation` unit tests for the `escape_bare_braces` helper.
    ///
    /// Verifies that:
    /// - `{N}`, `{N,}`, `{N,M}` quantifiers are left untouched.
    /// - `{{`, `{%`, `{[`, `!{` (non-quantifier) are escaped to `\{`.
    /// - Already-escaped `\{` is not double-escaped.
    /// - Character classes `[{]` are left alone (the `{` inside is already
    ///   literal in that context).
    #[test]
    fn test_escape_bare_braces_quantifiers_unchanged() {
        // Valid quantifiers must pass through unchanged.
        assert_eq!(escape_bare_braces(r"[A-Z]{20}"), r"[A-Z]{20}");
        assert_eq!(escape_bare_braces(r"foo{1,3}bar"), r"foo{1,3}bar");
        assert_eq!(escape_bare_braces(r"\w{8,}"), r"\w{8,}");
    }

    #[test]
    fn test_escape_bare_braces_template_syntax_escaped() {
        // Template syntax uses `{{` / `{%` without escaping — these must be
        // rewritten to `\{` forms so Rust's `regex` crate accepts them.
        let result = escape_bare_braces(r"{{.*?\|\s*safe(\s*}})?");
        // The compiled regex must be accepted by Rust's regex crate.
        Regex::new(&result).expect("normalised regex must compile");

        let result2 = escape_bare_braces(r"{%\s*autoescape\s+false\s*%}");
        Regex::new(&result2).expect("normalised regex must compile");

        let result3 = escape_bare_braces(r"!{.*?}");
        Regex::new(&result3).expect("normalised regex must compile");
    }

    #[test]
    fn test_escape_bare_braces_already_escaped_not_doubled() {
        // `\{` is already escaped; `escape_bare_braces` must not add another `\`.
        let input = r"\{foo\}";
        let result = escape_bare_braces(input);
        assert_eq!(
            result, input,
            "already-escaped braces must not be double-escaped"
        );
    }

    #[test]
    fn test_escape_bare_braces_inside_char_class_unchanged() {
        // `[{]` — `{` inside a character class is already literal; the
        // normalisation should leave it (and its surrounding class) intact.
        let input = r"[{}\s]*";
        let result = escape_bare_braces(input);
        Regex::new(&result).expect("normalised regex must compile");
    }

    /// `compile_regex` must keep using the fast `regex` crate for ordinary
    /// patterns that contain no PCRE-only features — the fancy-regex fallback
    /// is reserved for patterns the fast engine rejects.
    #[test]
    fn test_compile_regex_fast_path_for_plain_pattern() {
        let compiled = compile_regex(r"password\s*=").expect("plain pattern must compile");
        assert!(
            matches!(compiled, CompiledRegex::Fast(_)),
            "a pattern with no lookaround/backref must compile on the fast `regex` crate"
        );
        assert!(
            compiled.is_match("password = 'hunter2'"),
            "fast-path regex must match the obvious case"
        );
        assert!(
            !compiled.is_match("token = 'hunter2'"),
            "fast-path regex must not match unrelated text"
        );
        // The fast engine reports byte ranges just like the fancy one.
        assert_eq!(
            compiled.find_matches("x; password=1"),
            vec![(3, 12)],
            "fast-path find_matches must return the matched byte range"
        );
    }

    /// `compile_regex` must transparently fall back to the backtracking
    /// `fancy-regex` engine when the fast `regex` crate rejects a PCRE
    /// lookahead, and the resulting matcher must honour the lookahead.
    #[test]
    fn test_compile_regex_fancy_path_for_lookahead() {
        // Anchored negative lookahead: at the start of the string, match
        // `password =` only when it is NOT prefixed by `test_`. Anchoring with
        // `^` ties the negative lookahead to the whole-line result so the
        // exclusion is observable. The fast `regex` crate rejects `(?!...)`.
        let pattern = r"^(?!test_)password\s*=";
        assert!(
            Regex::new(pattern).is_err(),
            "sanity: the fast `regex` crate must reject this lookahead pattern"
        );

        let compiled = compile_regex(pattern).expect("lookahead pattern must compile via fallback");
        assert!(
            matches!(compiled, CompiledRegex::Fancy(_)),
            "a lookahead pattern must compile on the fancy-regex fallback engine"
        );

        // Real password assignment → the negative lookahead allows the match.
        assert!(
            compiled.is_match("password = 'secret'"),
            "fancy-path regex must match a non-test password assignment"
        );
        // `test_password =` → the `^` anchor pins the match attempt to position
        // 0, where the negative lookahead `(?!test_)` fails, so there is no
        // match anywhere.
        assert!(
            !compiled.is_match("test_password = 'secret'"),
            "fancy-path regex must reject a `test_`-prefixed password assignment"
        );
    }

    /// End-to-end: a `languages: [regex]` rule whose `pattern-regex` uses a PCRE
    /// lookahead now LOADS (previously warn-skipped as `loader rejected
    /// (other)`) and fires on the right source while sparing the excluded one.
    #[test]
    fn regex_lang_rule_with_lookahead_loads_and_matches() {
        let yaml = r#"
rules:
  - id: test/lookahead-password
    pattern-regex: '^(?!test_)password\s*='
    languages: [regex]
    message: Hardcoded password assignment
    severity: ERROR
"#;
        let f = make_yaml(yaml);
        let rules = parse_semgrep_file(f.path())
            .expect("lookahead pattern-regex rule must load via the fancy-regex fallback");
        assert!(
            !rules.is_empty(),
            "lookahead regex-mode rule must produce at least one rule instance"
        );

        // Source the rule SHOULD flag (real password assignment).
        let hit_src = "password = 'hunter2'\n";
        let tree = parse_file(hit_src, Language::Python).unwrap();
        let findings = rules[0].check(hit_src, &tree);
        assert!(
            !findings.is_empty(),
            "rule must fire on a non-test password assignment"
        );

        // Source the rule should NOT flag (the `test_` prefix is excluded by the
        // negative lookahead).
        let miss_src = "test_password = 'hunter2'\n";
        let tree = parse_file(miss_src, Language::Python).unwrap();
        let findings = rules[0].check(miss_src, &tree);
        assert!(
            findings.is_empty(),
            "rule must NOT fire when the negative lookahead excludes the match"
        );
    }

    /// Bridge-level test for the generic-mode lookahead lever. A
    /// `languages: [generic]` rule whose `pattern-regex` uses a negative
    /// lookahead (`(?!\S)`, the exact shape of the registry rule
    /// `google-maps-apikeyleak`) must now LOAD via `parse_semgrep_str` and FIRE
    /// through the scanner entrypoint (`rule.check`), with a safe near-miss.
    /// Previously the generic-mode `regex` crate rejected the lookahead and the
    /// rule produced no live matcher (counted as a generic-mode skip).
    #[test]
    fn generic_lang_rule_with_lookahead_loads_and_fires() {
        let yaml = r#"
rules:
  - id: test/generic-maps-apikey
    patterns:
      - pattern-regex: 'AIza[0-9A-Za-z_\-]{4}(?!\S)'
    languages: [generic]
    message: Detected a Google Maps API key
    severity: WARNING
"#;
        let rules = parse_semgrep_str(yaml, "generic-lookahead.yml")
            .expect("generic-mode rule with lookahead must load via fancy-regex");
        assert!(
            !rules.is_empty(),
            "generic-mode lookahead rule must produce at least one rule instance"
        );

        // Generic-mode rules ignore the tree; any valid tree satisfies the
        // `Rule::check` signature. The key must be at a token boundary: here it
        // is followed by whitespace, so the `(?!\S)` lookahead is satisfied.
        let firing = "key = AIza1234\nnext line\n";
        let tree = parse_file(firing, Language::JavaScript).unwrap();
        let findings = rules[0].check(firing, &tree);
        assert!(
            !findings.is_empty(),
            "generic lookahead rule must fire on a key followed by whitespace"
        );

        // Near-miss: the key token is immediately followed by another non-space
        // char, so the negative lookahead `(?!\S)` fails and nothing matches.
        let safe = "key = AIza1234EXTRA\n";
        let tree = parse_file(safe, Language::JavaScript).unwrap();
        let findings = rules[0].check(safe, &tree);
        assert!(
            findings.is_empty(),
            "generic lookahead rule must NOT fire when the lookahead is violated"
        );
    }

    // ── metavariable-type (search mode) ──────────────────────────────────────

    const METAVAR_TYPE_JAVA_RULE: &str = r#"
rules:
  - id: sql-execute-on-statement
    patterns:
      - pattern: $X.executeQuery($Q)
      - metavariable-type:
          metavariable: $X
          type: Statement
    message: executeQuery on a Statement
    severity: ERROR
    languages: [java]
"#;

    /// metavariable-type FIRES when the metavariable's declared type matches.
    #[test]
    fn test_metavariable_type_fires_on_matching_type() {
        let f = make_yaml(METAVAR_TYPE_JAVA_RULE);
        let rules = parse_semgrep_file(f.path()).expect("rule must load for java");
        assert_eq!(rules.len(), 1, "one java rule expected");

        let source = "class A { void m(String q) { Statement s; s.executeQuery(q); } }";
        let tree = parse_file(source, Language::Java).unwrap();
        let findings = rules[0].check(source, &tree);
        assert_eq!(
            findings.len(),
            1,
            "must fire when $X is declared as Statement"
        );
    }

    /// metavariable-type is SILENT when the declared type differs (a subtype
    /// with a name that merely *contains* the required type name must not match).
    #[test]
    fn test_metavariable_type_silent_on_wrong_type() {
        let f = make_yaml(METAVAR_TYPE_JAVA_RULE);
        let rules = parse_semgrep_file(f.path()).expect("rule must load for java");

        let source = "class A { void m(String q) { PreparedStatement p; p.executeQuery(q); } }";
        let tree = parse_file(source, Language::Java).unwrap();
        let findings = rules[0].check(source, &tree);
        assert!(
            findings.is_empty(),
            "must not fire when $X is a PreparedStatement, not a Statement"
        );
    }

    /// A parameter's declared type is resolvable too (not just locals).
    #[test]
    fn test_metavariable_type_resolves_parameter() {
        let f = make_yaml(METAVAR_TYPE_JAVA_RULE);
        let rules = parse_semgrep_file(f.path()).expect("rule must load for java");

        let fires = "class A { void m(Statement s, String q) { s.executeQuery(q); } }";
        let tree = parse_file(fires, Language::Java).unwrap();
        assert_eq!(
            rules[0].check(fires, &tree).len(),
            1,
            "must fire when the Statement is a method parameter"
        );

        let silent = "class A { void m(PreparedStatement s, String q) { s.executeQuery(q); } }";
        let tree = parse_file(silent, Language::Java).unwrap();
        assert!(
            rules[0].check(silent, &tree).is_empty(),
            "must not fire when the parameter is a PreparedStatement"
        );
    }

    /// Fully-qualified declared types match by simple name (`java.sql.Statement`
    /// satisfies `type: Statement`).
    #[test]
    fn test_metavariable_type_matches_qualified_name() {
        let f = make_yaml(METAVAR_TYPE_JAVA_RULE);
        let rules = parse_semgrep_file(f.path()).expect("rule must load for java");

        let source = "class A { void m(String q) { java.sql.Statement s; s.executeQuery(q); } }";
        let tree = parse_file(source, Language::Java).unwrap();
        assert_eq!(
            rules[0].check(source, &tree).len(),
            1,
            "qualified type java.sql.Statement must satisfy type: Statement"
        );
    }

    /// A `metavariable-type:` rule on a language with no syntactic type
    /// resolution (python) is SKIPPED by the loader rather than loaded with the
    /// constraint dropped (which would over-match).
    #[test]
    fn test_metavariable_type_unenforceable_language_skips_rule() {
        let yaml = r#"
rules:
  - id: py-concat
    patterns:
      - pattern: $X + $Y
      - metavariable-type:
          metavariable: $X
          type: str
    message: string concat
    severity: ERROR
    languages: [python]
"#;
        let f = make_yaml(yaml);
        let result = parse_semgrep_file(f.path());
        assert!(
            result.is_err(),
            "metavariable-type on python must cause the rule to be skipped, not loaded"
        );
    }
}