rs-runec 0.7.0

Compiler, linter, and language server for RuneScript, ClientScript, and GlobalScript, with ClientScript decompilation
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
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;

use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
use crate::clientscript;
use crate::diagnostic_messages as msg;
use crate::diagnostics::{
    Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
};
use crate::pointer::{PointerHolder, PointerSet, PointerType, command_pointers, trigger_pointers};
use crate::symbol::{SymbolKind, SymbolRegistry};
use crate::types::Type;

// ---------------------------------------------------------------------------
// CFG re-compile access trace (profiling only). Records the file whose CFG is
// built, so an LRU simulation can estimate the re-parse multiplier a streaming
// "re-compile on demand" pointer check would pay — measured before committing
// to that rearchitecture. Enabled by `RUNEC_TRACE_CFG`; built only with memprof.
// ---------------------------------------------------------------------------
#[cfg(feature = "memprof")]
static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());

#[cfg(feature = "memprof")]
fn cfg_trace_push(source_path: &str) {
    if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
        CFG_TRACE.lock().unwrap().push(source_path.to_string());
    }
}

/// Simulate an LRU file cache over the recorded CFG-build sequence and report
/// re-parse counts for several cache sizes (1.0x = each file parsed once).
#[cfg(feature = "memprof")]
pub(crate) fn cfg_trace_report() {
    use tracing::info;
    let trace = CFG_TRACE.lock().unwrap();
    if trace.is_empty() {
        return;
    }
    let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
    let nfiles = distinct.len().max(1);
    info!(
        "[trace] build_cfg calls: {}, distinct files: {}",
        trace.len(),
        nfiles
    );
    for &cap in &[16usize, 64, 256, 1024, nfiles] {
        let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
        let mut misses = 0usize;
        for f in trace.iter() {
            let f = f.as_str();
            if let Some(pos) = lru.iter().position(|x| *x == f) {
                lru.remove(pos);
            } else {
                misses += 1;
            }
            lru.insert(0, f);
            if lru.len() > cap {
                lru.pop();
            }
        }
        info!(
            "[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
            cap,
            misses,
            misses as f64 / nfiles as f64,
            nfiles
        );
    }
}

// ---------------------------------------------------------------------------
// Script source: resident slice (batch/stream) or recompile-on-demand (the
// `RUNEC_RECOMPILE` memory mode, which never holds all compiled scripts).
// ---------------------------------------------------------------------------

/// A script handle that is either borrowed from the resident slice (zero-cost)
/// or owned via an `Rc` from the recompile store. Derefs to `CompiledScript`, so
/// call sites read fields the same way regardless of mode.
pub(crate) enum ScriptRef<'a> {
    Borrowed(&'a CompiledScript),
    Owned(std::rc::Rc<CompiledScript>),
}

impl std::ops::Deref for ScriptRef<'_> {
    type Target = CompiledScript;
    fn deref(&self) -> &CompiledScript {
        match self {
            ScriptRef::Borrowed(s) => s,
            ScriptRef::Owned(rc) => rc,
        }
    }
}

/// Where the pointer checker gets a script's compiled form. `Resident` borrows
/// the already-compiled slice. `Recompile` calls back into a store that re-parses
/// and compiles the script on demand (bounded LRU), so the 13 MB of compiled
/// scripts need not be resident. The recompile getter is `FnMut` (mutates its
/// cache) and not `Sync`, so that mode runs the checker single-threaded.
pub(crate) enum ScriptSource<'a> {
    Resident(&'a [CompiledScript]),
    Recompile {
        len: usize,
        get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
    },
}

impl<'a> ScriptSource<'a> {
    fn len(&self) -> usize {
        match self {
            ScriptSource::Resident(s) => s.len(),
            ScriptSource::Recompile { len, .. } => *len,
        }
    }

    /// Fetch script `idx`. Borrowed (resident) carries the slice lifetime, not
    /// `&self`'s, so it doesn't pin a whole-`self` borrow — preserving the
    /// checker's disjoint field borrows (scripts vs the mutable caches).
    fn get(&self, idx: usize) -> ScriptRef<'a> {
        match self {
            ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
            ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
        }
    }
}

// ---------------------------------------------------------------------------
// Control flow graph node
// ---------------------------------------------------------------------------

#[derive(Debug)]
struct CfgNode {
    /// Index into `CompiledScript::instructions`, or `None` for synthetic nodes
    /// (start node, pointer-instruction nodes).
    instruction_index: Option<usize>,
    /// For pointer-instruction nodes: the set of pointers this node establishes.
    pointer_set: PointerSet,
    /// Successor node indices.
    next: Vec<usize>,
    /// Predecessor node indices.
    previous: Vec<usize>,
}

impl CfgNode {
    fn new(instruction_index: Option<usize>) -> Self {
        CfgNode {
            instruction_index,
            pointer_set: PointerSet::new(),
            next: Vec::new(),
            previous: Vec::new(),
        }
    }

    fn pointer_node(pointer_set: PointerSet) -> Self {
        CfgNode {
            instruction_index: None,
            pointer_set,
            next: Vec::new(),
            previous: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Per-script analysis result
// ---------------------------------------------------------------------------

struct ScriptAnalysis {
    nodes: Vec<CfgNode>,
    /// `required[ptr_index]` = list of node indices whose instruction requires this pointer.
    required: Vec<Vec<usize>>,
    /// `set_list[ptr_index]` = list of node indices that establish this pointer.
    set_list: Vec<Vec<usize>>,
    /// `corrupted_list[ptr_index]` = list of node indices that corrupt this pointer.
    corrupted_list: Vec<Vec<usize>>,
    /// Node indices of Return instructions.
    returns: Vec<usize>,
}

impl ScriptAnalysis {
    fn new() -> Self {
        let n = PointerType::COUNT;
        ScriptAnalysis {
            nodes: Vec::new(),
            required: vec![Vec::new(); n],
            set_list: vec![Vec::new(); n],
            corrupted_list: vec![Vec::new(); n],
            returns: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// PointerChecker
// ---------------------------------------------------------------------------

/// Read-only lookup tables derived once from the compiled scripts + registry.
/// Shared via `Arc` across the per-chunk checkers that run on worker threads,
/// so this (command-table-sized) data is built once per compile instead of once
/// per thread — the pointer-check pass otherwise rebuilt all of it ~N-cores times.
pub(crate) struct SharedMaps {
    client: bool,
    cmd_pointers: HashMap<String, PointerHolder>,
    /// Reverse map: command opcode -> command name (lowercase).
    opcode_to_name: HashMap<i32, String>,
    /// Reverse map: script id -> index into `scripts`.
    script_id_to_index: HashMap<i32, usize>,
    /// Reverse map: script name -> index into `scripts` (first occurrence wins,
    /// matching a linear `position(|s| s.name == name)` scan). Avoids an O(n)
    /// scan per `validate_script`/`ensure_analysis` call (O(n²) overall).
    script_name_to_index: HashMap<String, usize>,
    /// Overlay interface names (normalized lowercase). If_button/inv_button triggers
    /// for non-overlay interfaces grant p_active_player, matching ServerPointerChecker.
    overlay_interfaces: HashSet<String>,
}

pub struct PointerChecker<'a> {
    scripts: ScriptSource<'a>,
    #[allow(dead_code)]
    registry: &'a SymbolRegistry,
    /// Read-only lookup tables, shared (`Arc`) across worker threads.
    shared: std::sync::Arc<SharedMaps>,
    /// Optional source-text cache, keyed by `CompiledScript::source_path`.
    /// When present, the checker attaches rustc-style Help/Suggestion
    /// blocks to its warnings. When `None`, warnings still fire but carry
    /// no concrete fix text. Read-only; never feeds codegen.
    source_cache: Option<crate::SourceProvider<'a>>,
    // Caches
    script_analyses: HashMap<String, ScriptAnalysis>,
    script_pointers: HashMap<String, PointerHolder>,
    pending_analyses: HashSet<String>,
    pending_scripts: HashSet<String>,
    recursive_scripts: HashSet<String>,
}

impl SharedMaps {
    /// Build the read-only lookup tables from the script identities (id, name) +
    /// registry. Taking `(id, name)` idents rather than the compiled slice lets
    /// the recompile mode build these from lightweight metas (no held bytecode).
    fn build<'b>(
        idents: impl Iterator<Item = (i32, &'b str)>,
        registry: &SymbolRegistry,
        client: bool,
    ) -> Self {
        // Build reverse opcode -> name map from registry.commands
        let mut opcode_to_name = HashMap::new();
        for (name, sym) in &registry.commands {
            if let SymbolKind::Command { opcode, .. } = &sym.kind {
                opcode_to_name.insert(*opcode, name.to_lowercase());
            }
        }

        // Build reverse id->index and name->index maps. Insert only the first
        // name occurrence so lookups match a `position(|s| s.name == name)` scan
        // when multiple triggers share a name.
        let mut script_id_to_index = HashMap::new();
        let mut script_name_to_index = HashMap::new();
        for (i, (id, name)) in idents.enumerate() {
            script_id_to_index.insert(id, i);
            script_name_to_index.entry(name.to_string()).or_insert(i);
        }

        // Build overlay interface set from entity_ids (OverlayInterface type).
        // Any if_button/inv_button trigger whose interface is NOT in this set
        // gets p_active_player granted, matching ServerPointerChecker.
        let mut overlay_interfaces = HashSet::new();
        for (name, entry) in &registry.entity_ids {
            if entry
                .variants
                .iter()
                .any(|(t, _)| *t == Type::OverlayInterface)
            {
                overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
            }
        }

        SharedMaps {
            client,
            cmd_pointers: registry.profile.as_ref().map_or_else(
                || {
                    if client {
                        clientscript::command_pointers(registry)
                    } else {
                        command_pointers()
                    }
                },
                |profile| profile.command_pointers.clone(),
            ),
            opcode_to_name,
            script_id_to_index,
            script_name_to_index,
            overlay_interfaces,
        }
    }
}

impl<'a> PointerChecker<'a> {
    pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
        let shared = std::sync::Arc::new(SharedMaps::build(
            scripts.iter().map(|s| (s.id, s.name.as_str())),
            registry,
            false,
        ));
        Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
    }

    pub fn new_client(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
        let shared = std::sync::Arc::new(SharedMaps::build(
            scripts.iter().map(|s| (s.id, s.name.as_str())),
            registry,
            true,
        ));
        Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
    }

    /// Build the read-only lookup tables once, so a fleet of per-chunk checkers
    /// can share them across threads (`Arc::clone`) instead of each rebuilding
    /// the full command/script tables.
    pub(crate) fn build_shared(
        scripts: &[CompiledScript],
        registry: &SymbolRegistry,
        client: bool,
    ) -> std::sync::Arc<SharedMaps> {
        std::sync::Arc::new(SharedMaps::build(
            scripts.iter().map(|s| (s.id, s.name.as_str())),
            registry,
            client,
        ))
    }

    /// Build the shared maps for the recompile mode from lightweight `(id, name)`
    /// idents, so no compiled bytecode need be resident to construct them.
    pub(crate) fn build_shared_idents(
        idents: &[(i32, String)],
        registry: &SymbolRegistry,
    ) -> std::sync::Arc<SharedMaps> {
        std::sync::Arc::new(SharedMaps::build(
            idents.iter().map(|(id, name)| (*id, name.as_str())),
            registry,
            false,
        ))
    }

    /// Construct a checker over pre-built shared maps. Each worker thread gets
    /// its own checker (own memoization caches) but shares the read-only maps.
    pub(crate) fn with_shared(
        scripts: ScriptSource<'a>,
        registry: &'a SymbolRegistry,
        shared: std::sync::Arc<SharedMaps>,
    ) -> Self {
        PointerChecker {
            scripts,
            registry,
            shared,
            source_cache: None,
            script_analyses: HashMap::new(),
            script_pointers: HashMap::new(),
            pending_analyses: HashSet::new(),
            pending_scripts: HashSet::new(),
            recursive_scripts: HashSet::new(),
        }
    }

    /// Attach a source-text cache so emitted warnings can carry concrete
    /// before/after suggestion text. Purely diagnostic — never touches
    /// bytecode, script metadata, or output ordering.
    pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
        self.source_cache = Some(provider);
    }

    /// Check if an if_button/inv_button trigger on a non-overlay interface
    /// grants p_active_player. Matches ServerPointerChecker.setsPointerTrigger().
    fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
        if !self
            .registry
            .trigger(trigger)
            .is_some_and(|trigger| trigger.is_button)
        {
            return false;
        }
        // Extract interface name from script name: "[trigger,interface_name:component]"
        let subject = script_name
            .trim_start_matches('[')
            .trim_end_matches(']')
            .split_once(',')
            .map(|(_, rest)| rest)
            .unwrap_or("");
        let iface_name = subject
            .split(':')
            .next()
            .unwrap_or("")
            .to_lowercase()
            .replace(' ', "_");
        if iface_name.is_empty() {
            return false;
        }
        // Non-overlay interfaces grant p_active_player
        !self.shared.overlay_interfaces.contains(&iface_name)
    }

    /// Run pointer checking on all scripts and return collected diagnostics.
    pub fn run(&mut self) -> DiagnosticsCollector {
        let names = self.script_names();
        self.validate_names(&names)
    }

    /// Script names in validation order (the order of `scripts`).
    pub fn script_names(&self) -> Vec<String> {
        (0..self.scripts.len())
            .map(|i| self.scripts.get(i).name.clone())
            .collect()
    }

    /// Validate the given scripts, returning their diagnostics in `names` order.
    ///
    /// The per-script caches are pure memoization (a script's analysis is a
    /// function of the read-only scripts + registry), so splitting
    /// `script_names()` into chunks and giving each chunk its own
    /// `PointerChecker` produces byte-identical diagnostics to validating
    /// everything in a single checker — which lets the pass run across threads.
    pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
        self.validate_names_until(names, &|| false)
    }

    /// `validate_names`, giving up between scripts once `stop` returns true.
    pub(crate) fn validate_names_until(
        &mut self,
        names: &[String],
        stop: &dyn Fn() -> bool,
    ) -> DiagnosticsCollector {
        self.validate_names_with(names, stop, |_, _| {})
    }

    pub(crate) fn validate_names_with_requirements_until(
        &mut self,
        names: &[String],
        stop: &dyn Fn() -> bool,
    ) -> (DiagnosticsCollector, HashMap<String, PointerSet>) {
        let mut requirements = HashMap::new();
        let diagnostics = self.validate_names_with(names, stop, |checker, name| {
            if let Some(analysis) = checker.script_analyses.get(name) {
                let required = PointerType::ALL
                    .into_iter()
                    .filter(|pointer| {
                        let pi = pointer.index();
                        if analysis.required[pi].is_empty() {
                            return false;
                        }
                        let blocked = analysis.set_list[pi].iter().copied().collect();
                        Self::requires_at_entry(analysis, pi, &blocked)
                    })
                    .collect();
                requirements.insert(name.to_string(), required);
            }
        });
        (diagnostics, requirements)
    }

    fn validate_names_with(
        &mut self,
        names: &[String],
        stop: &dyn Fn() -> bool,
        mut on_script: impl FnMut(&Self, &str),
    ) -> DiagnosticsCollector {
        let mut diagnostics = DiagnosticsCollector::new();
        for script_name in names {
            if stop() {
                break;
            }
            self.validate_script(script_name, &mut diagnostics);
            on_script(self, script_name);
            // A script's CFG (and any callee CFGs built to derive summaries) is
            // only needed during its own validation; the cross-script pointer
            // summaries persist in `script_pointers`. Free the CFGs now so peak
            // scratch is ~one script's CFG instead of the whole chunk's — the
            // checker otherwise memoizes every analyzed CFG for the chunk's life.
            // (`build_rule_a_help` rebuilds a callee's CFG on demand if a later
            // warning needs it, so diagnostics are unchanged.)
            self.script_analyses.clear();
        }
        diagnostics
    }

    fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
        // Find the script
        let script_idx = match self.shared.script_name_to_index.get(script_name) {
            Some(&i) => i,
            None => return,
        };
        let trigger = self.scripts.get(script_idx).trigger.clone();
        let source_path = self.scripts.get(script_idx).source_path.clone();
        let trigger_set = if let Some(profile) = &self.registry.profile {
            profile
                .trigger_pointers
                .get(&trigger)
                .copied()
                .unwrap_or_default()
        } else if self.shared.client {
            match trigger.as_str() {
                "proc" => [PointerType::ActiveComponent, PointerType::ActiveComponent2]
                    .into_iter()
                    .collect(),
                _ => PointerSet::new(),
            }
        } else {
            trigger_pointers(&trigger)
        };

        // Ensure analysis exists
        self.ensure_analysis(script_name);

        if !self.shared.client && matches!(trigger.as_str(), "proc" | "label") {
            self.warn_implicit_context(script_idx, diagnostics);
        }

        for &ptr in &PointerType::ALL {
            let ptr_idx = ptr.index();

            // Get analysis data — we need to work with references carefully
            let analysis = match self.script_analyses.get(script_name) {
                Some(a) => a,
                None => continue,
            };

            let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
            if required_nodes.is_empty() {
                continue;
            }

            // Build corrupted set: start with the analysis corrupted nodes. The
            // CFG stores only the compact `corrupted_list` Vec; the BFS needs an
            // O(1) lookup set, so materialize one here (transient, dropped after
            // this pointer's check) rather than retaining a duplicate per CFG.
            let mut corrupted: HashSet<usize> =
                analysis.corrupted_list[ptr_idx].iter().copied().collect();

            // If the trigger doesn't set this pointer, add the start node (node 0) as corrupted.
            // Special case: if_button/inv_button triggers on non-overlay interfaces
            // grant p_active_player, matching ServerPointerChecker.
            let trigger_provides = if trigger_set.contains(ptr) {
                true
            } else if ptr == PointerType::PActivePlayer {
                self.interface_trigger_grants_protected(&trigger, script_name)
            } else {
                false
            };
            if !trigger_provides {
                corrupted.insert(0);
            }

            if corrupted.is_empty() {
                continue;
            }

            let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();

            // Try to find a path from a required node backwards to a corrupted node
            let path = self.find_edge_path(
                script_name,
                &required_nodes,
                |node_idx| corrupted.contains(&node_idx),
                &set_blocked,
            );

            let mut reported_via_main_bfs = false;
            if let Some(path) = path {
                if path.is_empty() {
                    continue;
                }
                reported_via_main_bfs = true;

                let end_node_idx = path[path.len() - 1];
                let start_node_idx = path[0];

                let is_start_node = end_node_idx == 0;
                let repr = ptr.representation();
                let static_only = is_static_only_pointer(ptr);

                // Use softer "stale reference" wording for last_* / find_*
                // pointers — those are not tracked by the runtime and the
                // scripts compile and run; "corrupted" overstates it. The
                // engine-tracked family keeps the strong wording because a
                // missing pointer there is a real pointerCheck crash.
                let error_msg = if is_start_node {
                    if static_only {
                        msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
                    } else {
                        msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
                    }
                } else if static_only {
                    msg::fmt(msg::POINTER_STALE, &[repr])
                } else {
                    msg::fmt(msg::POINTER_CORRUPTED, &[repr])
                };

                let analysis = self.script_analyses.get(script_name).unwrap();
                let script_ref = self.scripts.get(script_idx);
                let instructions = &script_ref.instructions;
                let req_line = analysis.nodes[start_node_idx]
                    .instruction_index
                    .map(|idx| resolve_line(instructions, idx))
                    .unwrap_or(0);

                // Pointer diagnostics are reported as warnings: they flag
                // real static-analysis findings but should not fail the
                // compile. Runtime pointer enforcement (via engine
                // `pointerCheck`) still catches genuine misuse.
                diagnostics.add(Diagnostic {
                    file: PathBuf::from(&source_path),
                    line: req_line,
                    column: 0,
                    message: error_msg,
                    severity: Severity::Warning,
                    phase: Phase::PointerCheck,
                    help: Vec::new(),
                });

                let read_hint = if static_only {
                    msg::fmt(msg::POINTER_READ_HERE, &[repr])
                } else {
                    msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
                };
                diagnostics.add(Diagnostic {
                    file: PathBuf::from(&source_path),
                    line: req_line,
                    column: 0,
                    message: read_hint,
                    severity: Severity::Info,
                    phase: Phase::PointerCheck,
                    help: Vec::new(),
                });

                if !is_start_node {
                    let corrupt_line = analysis.nodes[end_node_idx]
                        .instruction_index
                        .map(|idx| resolve_line(instructions, idx))
                        .unwrap_or(0);

                    let cause_hint = if static_only {
                        msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
                    } else {
                        msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
                    };
                    diagnostics.add(Diagnostic {
                        file: PathBuf::from(&source_path),
                        line: corrupt_line,
                        column: 0,
                        message: cause_hint,
                        severity: Severity::Info,
                        phase: Phase::PointerCheck,
                        help: Vec::new(),
                    });
                }
            }

            // Secondary check: flag nodes that simultaneously require AND
            // corrupt this pointer. The 2004scape TS PointerChecker does not
            // catch these (its BFS only inspects predecessors of required
            // nodes, never the required node itself), but they correspond to
            // real "@jump to a label that consumes then invalidates the
            // pointer" patterns that are worth surfacing.
            //
            // Only emit for static-only pointers (last_*, find_*). The
            // active_player / p_active_player / active_npc / active_loc /
            // active_obj family is runtime-tracked by the engine and, in
            // practice, the callers in these patterns do not access the
            // pointer again after the gosub, so flagging them is noise.
            if !reported_via_main_bfs && is_static_only_pointer(ptr) {
                // Collect the (node, line) pairs that both require and corrupt
                // this pointer, then drop the analysis borrow so help generation
                // can take `&mut self` (it may rebuild a cleared callee's CFG).
                let targets: Vec<(usize, usize)> = {
                    let analysis = self.script_analyses.get(script_name).unwrap();
                    let script_ref = self.scripts.get(script_idx);
                    let instructions = &script_ref.instructions;
                    let corrupted_nodes: HashSet<usize> =
                        analysis.corrupted_list[ptr_idx].iter().copied().collect();
                    required_nodes
                        .iter()
                        .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
                        .map(|&node_idx| {
                            let line = analysis.nodes[node_idx]
                                .instruction_index
                                .map(|idx| resolve_line(instructions, idx))
                                .unwrap_or(0);
                            (node_idx, line)
                        })
                        .collect()
                };
                let mut seen_lines: HashSet<usize> = HashSet::new();
                let repr = ptr.representation();
                for (node_idx, line) in targets {
                    if !seen_lines.insert(line) {
                        continue;
                    }

                    // Build a rustc-style Help pointing at the concrete fix:
                    // thread the pointer through the callee as a parameter.
                    // Falls back to prose-only if source cache is absent or
                    // the callee can't be identified.
                    let help =
                        self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);

                    // Secondary-heuristic warning: both "read here" and
                    // "superseded here" collapse to the same Jump/Gosub
                    // node, so the info hints from the main-BFS path would
                    // just triple-print the same source line. The Help
                    // block already pinpoints the call site and the label
                    // header with a concrete fix — skip the duplicate
                    // hints and use the softer stale wording.
                    let mut diag = Diagnostic {
                        file: PathBuf::from(&source_path),
                        line,
                        column: 0,
                        message: msg::fmt(msg::POINTER_STALE, &[repr]),
                        severity: Severity::Warning,
                        phase: Phase::PointerCheck,
                        help: Vec::new(),
                    };
                    if let Some(h) = help {
                        diag.help.push(h);
                    }
                    diagnostics.add(diag);
                }
            }
        }
    }

    fn warn_implicit_context(&self, script_idx: usize, diagnostics: &mut DiagnosticsCollector) {
        let script = self.scripts.get(script_idx);
        let Some(analysis) = self.script_analyses.get(&script.name) else {
            return;
        };
        for ptr in PointerType::ALL
            .into_iter()
            .filter(|ptr| is_static_only_pointer(*ptr))
        {
            let pi = ptr.index();
            if !analysis.required[pi].iter().any(|&node| {
                analysis.nodes[node]
                    .instruction_index
                    .is_some_and(|instruction| {
                        script.instructions[instruction].opcode == Opcode::Command
                    })
            }) {
                continue;
            }
            let blocked = analysis.set_list[pi]
                .iter()
                .chain(&analysis.corrupted_list[pi])
                .copied()
                .collect::<HashSet<_>>();
            let mut inherited = vec![false; analysis.nodes.len()];
            let mut pending = vec![0];
            while let Some(node) = pending.pop() {
                if inherited[node] {
                    continue;
                }
                inherited[node] = true;
                if !blocked.contains(&node) {
                    pending.extend(&analysis.nodes[node].next);
                }
            }
            let mut reported = HashSet::new();
            for &node in &analysis.required[pi] {
                let Some(instruction) = analysis.nodes[node].instruction_index else {
                    continue;
                };
                if !inherited[node] || script.instructions[instruction].opcode != Opcode::Command {
                    continue;
                }
                let line = resolve_line(&script.instructions, instruction);
                if reported.insert(line) {
                    diagnostics.warning(
                        PathBuf::from(&script.source_path),
                        line,
                        0,
                        msg::fmt(
                            msg::POINTER_IMPLICIT_CONTEXT,
                            &[ptr.representation(), &script.name],
                        ),
                        Phase::PointerCheck,
                    );
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // BFS path finding
    // -----------------------------------------------------------------------

    /// Find a path from any start node backwards through predecessor edges to
    /// a node satisfying `end_pred`, avoiding nodes in `blocked`.
    ///
    /// Returns the path from start to end (inclusive) if found.
    fn find_edge_path(
        &self,
        script_name: &str,
        starts: &[usize],
        end_pred: impl Fn(usize) -> bool,
        blocked: &HashSet<usize>,
    ) -> Option<Vec<usize>> {
        let analysis = self.script_analyses.get(script_name)?;

        let mut queue: VecDeque<usize> = VecDeque::new();
        let mut visited: HashSet<usize> = HashSet::new();
        // Track which node led us to each node, plus which start node originated this path
        let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); // node -> (from_node, start_node)

        // Seed BFS: for each start node, add its predecessors.
        // Matches TS: we do NOT check start nodes themselves against the end predicate.
        // This prevents false positives when a Gosub node is both required and corrupted
        // for the same pointer (the requirement is satisfied first within the proc).
        for &start in starts {
            for &prev in &analysis.nodes[start].previous {
                if blocked.contains(&prev) || visited.contains(&prev) {
                    continue;
                }
                visited.insert(prev);
                queue.push_back(prev);
                sources.insert(prev, (start, start));
            }
        }

        while let Some(current) = queue.pop_front() {
            if end_pred(current) {
                // Reconstruct path from current back to start
                let mut path = vec![current];
                let mut node = current;
                while let Some(&(from, start)) = sources.get(&node) {
                    if from == start && starts.contains(&from) {
                        path.push(from);
                        break;
                    }
                    path.push(from);
                    node = from;
                }
                path.reverse();
                return Some(path);
            }

            let (_, start_node) = sources[&current];

            for &prev in &analysis.nodes[current].previous {
                if blocked.contains(&prev) || visited.contains(&prev) {
                    continue;
                }
                visited.insert(prev);
                queue.push_back(prev);
                sources.insert(prev, (current, start_node));
            }
        }

        None
    }

    /// Static version of find_edge_path that operates on nodes directly,
    /// used by get_script_pointers where we can't borrow &self.
    fn find_edge_path_static(
        nodes: &[CfgNode],
        starts: &[usize],
        end_pred: impl Fn(usize) -> bool,
        blocked: &HashSet<usize>,
    ) -> Option<Vec<usize>> {
        let mut queue: VecDeque<usize> = VecDeque::new();
        let mut visited: HashSet<usize> = HashSet::new();
        let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();

        for &start in starts {
            for &prev in &nodes[start].previous {
                if blocked.contains(&prev) || visited.contains(&prev) {
                    continue;
                }
                visited.insert(prev);
                queue.push_back(prev);
                sources.insert(prev, (start, start));
            }
        }

        while let Some(current) = queue.pop_front() {
            if end_pred(current) {
                let mut path = vec![current];
                let mut node = current;
                while let Some(&(from, start)) = sources.get(&node) {
                    if from == start && starts.contains(&from) {
                        path.push(from);
                        break;
                    }
                    path.push(from);
                    node = from;
                }
                path.reverse();
                return Some(path);
            }

            for &prev in &nodes[current].previous {
                if blocked.contains(&prev) || visited.contains(&prev) {
                    continue;
                }
                visited.insert(prev);
                queue.push_back(prev);
                sources.insert(prev, (current, sources[&current].1));
            }
        }

        None
    }

    // -----------------------------------------------------------------------
    // Analysis
    // -----------------------------------------------------------------------

    fn ensure_analysis(&mut self, script_name: &str) {
        if self.script_analyses.contains_key(script_name) {
            return;
        }
        if self.pending_analyses.contains(script_name) {
            self.mark_recursive_scripts();
            return;
        }
        self.pending_analyses.insert(script_name.to_string());

        let script_idx = match self.shared.script_name_to_index.get(script_name) {
            Some(&i) => i,
            None => return,
        };

        let mut analysis = self.build_cfg(script_idx);
        self.categorize_nodes(script_idx, &mut analysis);

        self.script_analyses
            .insert(script_name.to_string(), analysis);
        if !self.recursive_scripts.is_empty() {
            self.recursive_scripts.insert(script_name.to_string());
        }
        self.pending_analyses.remove(script_name);
        self.resolve_recursive_scripts();
    }

    fn mark_recursive_scripts(&mut self) {
        self.recursive_scripts
            .extend(self.pending_analyses.iter().cloned());
        self.recursive_scripts
            .extend(self.pending_scripts.iter().cloned());
    }

    fn resolve_recursive_scripts(&mut self) {
        if self.recursive_scripts.is_empty()
            || !self.pending_analyses.is_empty()
            || !self.pending_scripts.is_empty()
        {
            return;
        }
        let mut names: Vec<_> = self.recursive_scripts.drain().collect();
        names.sort();
        // Requirements and possible corruption grow from empty; guaranteed
        // setters shrink from all pointers until recursive summaries agree.
        for name in &names {
            self.script_pointers.insert(
                name.clone(),
                PointerHolder {
                    set: PointerSet::all(),
                    ..PointerHolder::default()
                },
            );
        }
        loop {
            let mut updates = Vec::with_capacity(names.len());
            for name in &names {
                let idx = self.shared.script_name_to_index[name];
                let mut analysis = self.build_cfg(idx);
                self.categorize_nodes(idx, &mut analysis);
                let holder = Self::analyzed_pointers(&analysis);
                updates.push((name.clone(), analysis, holder));
            }
            let mut changed = false;
            for (name, analysis, holder) in updates {
                changed |= self.script_pointers[&name] != holder;
                self.script_analyses.insert(name.clone(), analysis);
                self.script_pointers.insert(name, holder);
            }
            if !changed {
                break;
            }
        }
    }

    // -----------------------------------------------------------------------
    // CFG construction
    // -----------------------------------------------------------------------

    fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
        let script = self.scripts.get(script_idx);
        #[cfg(feature = "memprof")]
        cfg_trace_push(&script.source_path);
        let instructions = &script.instructions;
        let mut analysis = ScriptAnalysis::new();

        // Node 0 = start node (no instruction)
        analysis.nodes.push(CfgNode::new(None));

        // Map instruction index -> CFG node index (skipping LineNumber instructions)
        let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
        let mut node_order: Vec<usize> = Vec::new(); // instruction indices in order

        for (i, instr) in instructions.iter().enumerate() {
            if instr.opcode == Opcode::LineNumber {
                continue;
            }
            let node_idx = analysis.nodes.len();
            instr_to_node.insert(i, node_idx);
            node_order.push(i);
            analysis.nodes.push(CfgNode::new(Some(i)));
        }

        if node_order.is_empty() {
            return analysis;
        }

        // Connect start node to first instruction node
        let first_node = instr_to_node[&node_order[0]];
        add_edge(&mut analysis.nodes, 0, first_node);

        // Build edges based on instruction semantics
        for (order_idx, &instr_idx) in node_order.iter().enumerate() {
            let node_idx = instr_to_node[&instr_idx];
            let instr = &instructions[instr_idx];

            let is_terminal = matches!(
                instr.opcode,
                Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
            );

            // Handle jump targets for branches (conditional and unconditional).
            // Jump targets often land on a LineNumber instruction (emitted for the
            // body's first source line); LineNumbers are not in `instr_to_node`, so
            // walk forward to the first real instruction before resolving.
            match instr.opcode {
                Opcode::Branch
                | Opcode::BranchNot
                | Opcode::BranchEquals
                | Opcode::BranchLessThan
                | Opcode::BranchGreaterThan
                | Opcode::BranchLessThanOrEquals
                | Opcode::BranchGreaterThanOrEquals
                | Opcode::LongBranchNot
                | Opcode::LongBranchEquals
                | Opcode::LongBranchLessThan
                | Opcode::LongBranchGreaterThan
                | Opcode::LongBranchLessThanOrEquals
                | Opcode::LongBranchGreaterThanOrEquals
                | Opcode::ObjBranchEquals
                | Opcode::ObjBranchNot
                | Opcode::BranchIfTrue
                | Opcode::BranchIfFalse => {
                    if let Operand::JumpTarget(target_instr_idx) = &instr.operand
                        && let Some(target_node) =
                            resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
                    {
                        add_edge(&mut analysis.nodes, node_idx, target_node);
                    }
                }

                Opcode::Switch => {
                    if let Operand::SwitchTable(tbl_idx) = &instr.operand {
                        let cases = &script.switch_tables[*tbl_idx as usize];
                        for &(_, target_instr_idx) in cases.iter() {
                            if let Some(target_node) =
                                resolve_target_node(target_instr_idx, instructions, &instr_to_node)
                            {
                                add_edge(&mut analysis.nodes, node_idx, target_node);
                            }
                        }
                    }
                }

                _ => {}
            }

            // Add fallthrough edge (next non-LineNumber instruction) for non-terminal instructions
            if !is_terminal
                && let Some(next_order_idx) = order_idx.checked_add(1)
                && next_order_idx < node_order.len()
            {
                let next_node = instr_to_node[&node_order[next_order_idx]];
                add_edge(&mut analysis.nodes, node_idx, next_node);
            }

            // For conditional branches: also add fallthrough
            // (already handled above since conditional branches are not terminal)

            // Track Return nodes
            if instr.opcode == Opcode::Return {
                analysis.returns.push(node_idx);
            }
        }

        // Pointer inversion: detect Command -> PushConstantInt(0/1) -> BranchEquals patterns
        self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);

        analysis
    }

    /// Detect conditional pointer setting patterns and insert synthetic
    /// PointerInstructionNode nodes.
    fn insert_pointer_nodes(
        &self,
        script_idx: usize,
        analysis: &mut ScriptAnalysis,
        instr_to_node: &HashMap<usize, usize>,
        node_order: &[usize],
    ) {
        let script_ref = self.scripts.get(script_idx);
        let instructions = &script_ref.instructions;

        // The branch must consume the find result itself. Earlier commands may
        // have had their result discarded or stored before an unrelated condition.
        for window_end in 1..node_order.len() {
            let branch_instr_idx = node_order[window_end];
            let branch_instr = &instructions[branch_instr_idx];
            let (push_value, scan_end) = match branch_instr.opcode {
                Opcode::BranchIfTrue => (1, window_end),
                Opcode::BranchIfFalse => (0, window_end),
                Opcode::BranchEquals | Opcode::BranchNot => {
                    let push_instr = &instructions[node_order[window_end - 1]];
                    match (push_instr.opcode, &push_instr.operand) {
                        (Opcode::PushConstantInt, Operand::Int(value @ (0 | 1))) => (
                            if branch_instr.opcode == Opcode::BranchNot {
                                1 - value
                            } else {
                                *value
                            },
                            window_end - 1,
                        ),
                        _ => continue,
                    }
                }
                _ => continue,
            };

            let Some(&cmd_instr_idx) = scan_end.checked_sub(1).and_then(|idx| node_order.get(idx))
            else {
                continue;
            };
            let cmd_instr = &instructions[cmd_instr_idx];
            if cmd_instr.opcode != Opcode::Command {
                continue;
            }

            // Look up command pointer info
            let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
            let cmd_name = match cmd_name {
                Some(n) => n,
                None => continue,
            };

            let holder = match self.shared.cmd_pointers.get(&cmd_name) {
                Some(h) => h,
                None => continue,
            };

            if !holder.conditional_set {
                continue;
            }

            if holder.set.is_empty() {
                continue;
            }

            let branch_node_idx = instr_to_node[&branch_instr_idx];

            // Create a synthetic pointer node with the command's set pointers
            let ptr_node_idx = analysis.nodes.len();
            analysis.nodes.push(CfgNode::pointer_node(holder.set));

            if push_value == 0 {
                // Inverted conditional: pointer is set when the branch is NOT taken
                // (i.e., the fallthrough path after BranchEquals).
                // The BranchEquals jumps when equal (value == 0 means "not found"),
                // so the fallthrough means "found" -> pointer is set.
                //
                // Insert pointer node between BranchEquals and its fallthrough target.
                // BranchEquals fallthrough = the next node in sequence after BranchEquals.
                let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
                    .next
                    .iter()
                    .copied()
                    .filter(|&n| {
                        // fallthrough target = not the jump target
                        if let Operand::JumpTarget(target) = &branch_instr.operand
                            && let Some(jump_node) =
                                resolve_target_node(*target, instructions, instr_to_node)
                        {
                            return n != jump_node;
                        }
                        true
                    })
                    .collect();

                for ft_target in fallthrough_targets {
                    // Remove edge: branch -> fallthrough
                    remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
                    // Add: branch -> ptr_node -> fallthrough
                    add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
                    add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
                }
            } else {
                // push_value == 1: pointer is set when the branch IS taken
                // BranchEquals jumps when equal (value == 1 means "found"),
                // so the jump target means "found" -> pointer is set.
                if let Operand::JumpTarget(target) = &branch_instr.operand
                    && let Some(jump_target_node) =
                        resolve_target_node(*target, instructions, instr_to_node)
                {
                    // Remove edge: branch -> jump_target
                    remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
                    // Add: branch -> ptr_node -> jump_target
                    add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
                    add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // Node categorization
    // -----------------------------------------------------------------------

    fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
        let script_ref = self.scripts.get(script_idx);
        let instructions = &script_ref.instructions;

        for node_idx in 0..analysis.nodes.len() {
            let instr_idx = match analysis.nodes[node_idx].instruction_index {
                Some(i) => i,
                None => {
                    // Synthetic pointer node — categorize its set pointers
                    let ptr_set = analysis.nodes[node_idx].pointer_set;
                    if !ptr_set.is_empty() {
                        for ptr in ptr_set.iter() {
                            let pi = ptr.index();
                            analysis.set_list[pi].push(node_idx);
                        }
                    }
                    continue;
                }
            };

            let instr = &instructions[instr_idx];

            match instr.opcode {
                Opcode::Command => {
                    let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
                    if let Some(name) = cmd_name
                        && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
                    {
                        self.apply_holder(analysis, node_idx, &holder);
                    }
                }

                Opcode::Gosub | Opcode::GosubWithParams => {
                    if let Operand::Int(script_id) = &instr.operand {
                        let callee_holder = self.get_script_pointers(*script_id);
                        self.apply_holder(analysis, node_idx, &callee_holder);
                    }
                }

                Opcode::Jump | Opcode::JumpWithParams => {
                    if let Operand::Int(script_id) = &instr.operand {
                        let callee_holder = self.get_script_pointers(*script_id);
                        self.apply_holder(analysis, node_idx, &callee_holder);
                    }
                }

                // Var reads/writes: dot-prefixed sources (`.%v`) route to the
                // secondary active_* pointer. The compiler encodes this by
                // setting bit 16 of the operand (see compiler.rs, where
                // secondary game vars emit `(1 << 16) | var_id`). TS emits
                // distinct opcodes (PushVar/PushVar2); we flatten that into a
                // single opcode + operand flag and recover it here.
                Opcode::PushVarp
                | Opcode::PushVarpBit
                | Opcode::PushVarcInt
                | Opcode::PushVarcString
                | Opcode::PushVarClan
                | Opcode::PushClanSettingInt
                | Opcode::PushClanSettingVarbit
                | Opcode::PushClanSettingLong
                | Opcode::PushClanSettingString
                    if !self.shared.client =>
                {
                    let pi = if is_secondary_var_operand(&instr.operand) {
                        PointerType::ActivePlayer2.index()
                    } else {
                        PointerType::ActivePlayer.index()
                    };
                    analysis.required[pi].push(node_idx);
                }

                Opcode::PopVarp
                | Opcode::PopVarpBit
                | Opcode::PopVarcInt
                | Opcode::PopVarcString
                | Opcode::PopVarClan
                | Opcode::PopClanSettingInt
                | Opcode::PopClanSettingVarbit
                | Opcode::PopClanSettingLong
                | Opcode::PopClanSettingString
                    if !self.shared.client =>
                {
                    let pi = if is_secondary_var_operand(&instr.operand) {
                        PointerType::ActivePlayer2.index()
                    } else {
                        PointerType::ActivePlayer.index()
                    };
                    analysis.required[pi].push(node_idx);
                }

                Opcode::PushVarn | Opcode::PopVarn | Opcode::PushVarnBit | Opcode::PopVarnBit
                    if !self.shared.client =>
                {
                    let pi = if is_secondary_var_operand(&instr.operand) {
                        PointerType::ActiveNpc2.index()
                    } else {
                        PointerType::ActiveNpc.index()
                    };
                    analysis.required[pi].push(node_idx);
                }

                Opcode::PushVarCon
                | Opcode::PopVarCon
                | Opcode::PushVarConBit
                | Opcode::PopVarConBit
                    if !self.shared.client =>
                {
                    let pi = if is_secondary_var_operand(&instr.operand) {
                        PointerType::ActiveController2.index()
                    } else {
                        PointerType::ActiveController.index()
                    };
                    analysis.required[pi].push(node_idx);
                }

                // PushVars/PopVars are global server vars — no pointer requirements
                _ => {}
            }
        }
    }

    fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
        for ptr in holder.required.iter() {
            let pi = ptr.index();
            analysis.required[pi].push(node_idx);
        }
        for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
            let pi = ptr.index();
            analysis.set_list[pi].push(node_idx);
        }
        for ptr in holder.corrupted.iter() {
            let pi = ptr.index();
            analysis.corrupted_list[pi].push(node_idx);
        }
    }

    // -----------------------------------------------------------------------
    // Callee pointer resolution
    // -----------------------------------------------------------------------

    fn requires_at_entry(
        analysis: &ScriptAnalysis,
        pointer: usize,
        setters: &HashSet<usize>,
    ) -> bool {
        Self::find_edge_path_static(
            &analysis.nodes,
            &analysis.required[pointer],
            |node_idx| node_idx == 0,
            setters,
        )
        .is_some()
    }

    /// Get the merged pointer requirements/effects of a called script.
    ///
    /// Uses graph reachability (matching the TS `calculatePointers`):
    /// - **requires**: is there a path from a required-node backwards to graph[0]
    ///   without passing through a setter? If yes, the script needs this pointer
    ///   from its caller.
    /// - **sets**: is there any return-path that reaches graph[0] or a corruptor
    ///   without passing through a setter? If NO such path, the script guarantees
    ///   the pointer is set on all exit paths.
    /// - **corrupts**: is there a return-path that reaches a corruptor without
    ///   passing through a setter? If yes, the script may corrupt this pointer.
    fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
        // Find script by ID
        let script_idx = match self.shared.script_id_to_index.get(&script_id) {
            Some(&i) => i,
            None => {
                return PointerHolder::default();
            }
        };
        let script_name = self.scripts.get(script_idx).name.clone();

        // Check cache
        if let Some(holder) = self.script_pointers.get(&script_name) {
            return holder.clone();
        }

        // Cycle detection
        if self.pending_scripts.contains(&script_name) {
            self.mark_recursive_scripts();
            return PointerHolder::default();
        }
        self.pending_scripts.insert(script_name.clone());

        // Ensure analysis exists
        self.ensure_analysis(&script_name);

        let holder = self
            .script_analyses
            .get(&script_name)
            .map_or_else(PointerHolder::default, Self::analyzed_pointers);
        self.pending_scripts.remove(&script_name);
        self.script_pointers.insert(script_name.clone(), holder);
        self.resolve_recursive_scripts();
        self.script_pointers[&script_name].clone()
    }

    fn analyzed_pointers(analysis: &ScriptAnalysis) -> PointerHolder {
        let mut holder = PointerHolder::default();
        for &ptr in &PointerType::ALL {
            let pi = ptr.index();

            // Both BFS walks below treat setter nodes as blocking. The CFG
            // stores only the compact `set_list`/`corrupted_list` Vecs, so
            // build the O(1) lookup sets on demand here (transient, freed at
            // the end of this iteration) instead of caching a duplicate
            // HashSet per pointer type in every memoized CFG.
            let requires = !analysis.required[pi].is_empty();
            let has_returns = !analysis.returns.is_empty();
            if !requires && !has_returns {
                continue;
            }
            let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();

            // requiresPointerScript: BFS from required → graph[0], blocked by setters
            if requires && Self::requires_at_entry(analysis, pi, &set_blocked) {
                holder.required.insert(ptr);
            }

            if has_returns {
                let corrupted_nodes: HashSet<usize> =
                    analysis.corrupted_list[pi].iter().copied().collect();

                // setsPointerScript: BFS from returns → (graph[0] OR corruptor),
                // blocked by setters. If NO path found, the script guarantees set.
                let path = Self::find_edge_path_static(
                    &analysis.nodes,
                    &analysis.returns,
                    |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
                    &set_blocked,
                );
                if path.is_none() {
                    holder.set.insert(ptr);
                }

                // corruptsPointerScript: BFS from returns → corruptor, blocked by setters
                if !corrupted_nodes.is_empty() {
                    let path = Self::find_edge_path_static(
                        &analysis.nodes,
                        &analysis.returns,
                        |node_idx| corrupted_nodes.contains(&node_idx),
                        &set_blocked,
                    );
                    if path.is_some() {
                        holder.corrupted.insert(ptr);
                    }
                }
            }
        }
        holder
    }

    // -----------------------------------------------------------------------
    // Command name resolution
    // -----------------------------------------------------------------------

    /// Walk the callee's analyzed CFG and return every instruction that
    /// put `ptr` into `corrupted_list` — a direct `Command(p_delay)`,
    /// a `Gosub(~chatnpc)` whose callee transitively corrupts the
    /// pointer, etc. Each entry is `(display_name, source_line)`.
    /// Results are deduplicated by `(name, line)`.
    fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
        let callee = self.scripts.get(callee_idx);
        let analysis = match self.script_analyses.get(&callee.name) {
            Some(a) => a,
            None => return Vec::new(),
        };
        let ptr_idx = ptr.index();
        let mut seen: HashSet<(String, usize)> = HashSet::new();
        let mut result: Vec<(String, usize)> = Vec::new();

        for &node_idx in &analysis.corrupted_list[ptr_idx] {
            let instr_idx = match analysis.nodes[node_idx].instruction_index {
                Some(i) => i,
                None => continue,
            };
            let instr = &callee.instructions[instr_idx];
            let line = resolve_line(&callee.instructions, instr_idx);

            let name = match instr.opcode {
                Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
                    Some(n) => n,
                    None => continue,
                },
                Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
                    Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
                        Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
                            .map(|s| format!("~{}", s))
                            .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
                        None => continue,
                    },
                    _ => continue,
                },
                // Jumps are terminal — they don't contribute to a
                // return-path corruption (the proc/label that @jumps out
                // is flagged via its own gosub/jump inheritance).
                _ => continue,
            };

            let key = (name.clone(), line);
            if seen.insert(key) {
                result.push((name, line));
            }
        }

        result
    }

    fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
        match &instr.operand {
            Operand::Int(encoded) => {
                let opcode = encoded & 0xFFFF;
                let secondary = (encoded >> 16) & 1;
                let base_name = self.shared.opcode_to_name.get(&opcode)?;
                if secondary == 1 {
                    Some(format!(".{}", base_name))
                } else {
                    Some(base_name.clone())
                }
            }
            Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
            _ => None,
        }
    }

    // -----------------------------------------------------------------------
    // Suggestion builder: Rule A — thread `last_*` through the callee
    // -----------------------------------------------------------------------
    //
    // Given a jump/gosub node that secondary-flagged for a static-only
    // pointer, produce a rustc-style Help with two Suggestions:
    //   1. rewrite the caller line to pass the captured pointer as an arg
    //   2. append a matching parameter to the callee's label/proc header
    //
    // Falls back to `None` when the source cache is absent or the callee
    // cannot be identified — the warning itself still fires.
    fn build_rule_a_help(
        &mut self,
        ptr: PointerType,
        caller_source_path: &str,
        caller_line: usize,
        node_idx: usize,
        caller_script_idx: usize,
    ) -> Option<Help> {
        // Resolve the jump/gosub target from the caller's CFG node, then drop
        // the borrow so the callee's analysis can be (re)built below.
        let (is_gosub, script_id) = {
            let caller = self.scripts.get(caller_script_idx);
            let analysis = self.script_analyses.get(&caller.name)?;
            let instr_idx = analysis.nodes[node_idx].instruction_index?;
            let instr = &caller.instructions[instr_idx];
            // Only Jump/Gosub nodes drive Rule A.
            match instr.opcode {
                Opcode::Jump | Opcode::JumpWithParams => (
                    false,
                    match &instr.operand {
                        Operand::Int(id) => *id,
                        _ => return None,
                    },
                ),
                Opcode::Gosub | Opcode::GosubWithParams => (
                    true,
                    match &instr.operand {
                        Operand::Int(id) => *id,
                        _ => return None,
                    },
                ),
                _ => return None,
            }
        };

        let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
        // The callee's CFG may have been freed (CFG caches are cleared between
        // top-level scripts to bound memory); rebuild it — a no-op if cached —
        // so `corruptors_in_callee` can name the specific superseding command.
        let callee_name = self.scripts.get(callee_idx).name.clone();
        self.ensure_analysis(&callee_name);

        let callee = self.scripts.get(callee_idx);
        let callee_source = callee.source_path.clone();

        // Derive the callee's `[trigger,name]` header line. The first
        // LineNumber instruction points at the *body's* first statement,
        // which is usually one line below the header — but not always
        // (blank lines, doc comments can shift it). Instead, scan the
        // source directly for the unambiguous `[<trigger>,<short>]`
        // pattern and fall back to the LineNumber estimate if the source
        // cache isn't attached.
        let first_body_line = callee
            .instructions
            .iter()
            .find_map(|i| match (i.opcode, &i.operand) {
                (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
                _ => None,
            })
            .unwrap_or(1);
        let callee_trigger = callee.trigger.clone();
        let callee_short_early = callee
            .name
            .trim_start_matches('[')
            .trim_end_matches(']')
            .split_once(',')
            .map(|(_, n)| n.to_string())
            .unwrap_or_else(|| callee.name.clone());
        let callee_header_line = self
            .source_cache
            .and_then(|c| c.get(&callee_source))
            .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
            .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));

        let ptr_cmd = ptr.representation(); // "last_useitem", "last_item", …
        let param_type = pointer_param_type(ptr);
        let param_name = format!("${}", ptr_cmd);

        let callee_short = callee
            .name
            .trim_start_matches('[')
            .trim_end_matches(']')
            .split_once(',')
            .map(|(_, n)| n.to_string())
            .unwrap_or_else(|| callee.name.clone());

        let arrow = if is_gosub { "~" } else { "@" };

        // Pull the specific corruptor(s) from the callee's own analysis
        // so the help message names what actually supersedes the pointer
        // (e.g. `p_delay` at line 21, or `~chatnpc` at line 11) rather
        // than saying "a delay or subroutine" generically.
        let corruptors = self.corruptors_in_callee(callee_idx, ptr);
        let corruptor_phrase = format_corruptors(&corruptors);

        let message = format!(
            "`{callee}` reads `{ptr}` then {phrase}; the script still \
             compiles and runs, but the reference is brittle to reorder. \
             Consider capturing `{ptr}` at the call site and threading it \
             through `{callee}` as an `{ty} {pname}` parameter so the \
             value is explicit and stable.",
            callee = callee_short,
            ptr = ptr_cmd,
            phrase = corruptor_phrase,
            ty = param_type,
            pname = param_name,
        );

        let cache = match self.source_cache {
            Some(c) => c,
            None => {
                // Prose-only fallback — still useful even without source text.
                return Some(Help {
                    message,
                    suggestions: Vec::new(),
                    applicability: Applicability::Unspecified,
                });
            }
        };

        let mut suggestions = Vec::new();

        // (1) Caller rewrite: insert the captured pointer as an argument
        // to the @label/~proc call on `caller_line`.
        if let Some(src) = cache.get(caller_source_path)
            && let Some(line_text) = nth_source_line(&src, caller_line)
            && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
        {
            suggestions.push(Suggestion {
                file: PathBuf::from(caller_source_path),
                line_range: (caller_line, caller_line),
                replacement: rewritten,
                label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
            });
        }

        // (2) Callee rewrite: append `<ty> <name>` to the header's param list.
        if let Some(src) = cache.get(&callee_source)
            && let Some(header_text) = nth_source_line(&src, callee_header_line)
            && let Some(rewritten) =
                rewrite_header_add_param(header_text, &callee_short, param_type, &param_name)
        {
            suggestions.push(Suggestion {
                file: PathBuf::from(&callee_source),
                line_range: (callee_header_line, callee_header_line),
                replacement: rewritten,
                label: Some(format!(
                    "at the `{}` header (add `{} {}`)",
                    callee_short, param_type, param_name
                )),
            });
        }

        Some(Help {
            message,
            suggestions,
            // The rewrite may collide with an existing local named after the
            // pointer, or with an existing param list that already contains
            // the value under a different name — human review recommended.
            applicability: Applicability::MaybeIncorrect,
        })
    }
}

// ---------------------------------------------------------------------------
// Graph edge helpers
// ---------------------------------------------------------------------------

fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
    if !nodes[from].next.contains(&to) {
        nodes[from].next.push(to);
    }
    if !nodes[to].previous.contains(&from) {
        nodes[to].previous.push(from);
    }
}

/// The 2004scape engine tracks `active_player`, `active_npc`, `active_loc`,
/// `active_obj`, their `.`-prefixed secondary variants, and
/// `p_active_player`/`p_active_player2` via `ScriptState.pointerCheck` at
/// runtime. `last_*` and `find_*` pointers are *not* tracked at runtime —
/// they are a compile-time discipline only (see the `last_useitem` handler
/// in PlayerOps.ts, which gates on `state.trigger`, not a runtime pointer).
///
/// The "requires AND corrupts at the same node" heuristic (a Jump/Gosub
/// inheriting `required | corrupted` from its callee) produces real
/// findings for the static-only set but is typically noise for the
/// engine-tracked set — callers in that pattern rarely touch the pointer
/// after the jump, so the engine's runtime check never fires.
fn is_static_only_pointer(ptr: PointerType) -> bool {
    use PointerType::*;
    matches!(
        ptr,
        FindPlayer
            | FindNpc
            | FindLoc
            | FindObj
            | FindDb
            | LastCom
            | LastInt
            | LastItem
            | LastSlot
            | LastTargetslot
            | LastUseitem
            | LastUseslot
            | LastString
            | LastCoord
    )
}

/// Strip the `[trigger,name]` brackets from a script's full name and
/// return just the `name` half, for display in help messages.
fn short_script_name(full_name: &str) -> Option<String> {
    full_name
        .trim_start_matches('[')
        .trim_end_matches(']')
        .split_once(',')
        .map(|(_, n)| n.to_string())
}

/// Render a list of `(name, line)` corruptors into the clause slot
/// in the help message. Empty → generic fallback; 1 → `calls `X` at line N`;
/// 2 → `calls `X` at line N and `Y` at line M`; 3+ → list with commas
/// and a trailing "and", truncated after 3 with "…".
fn format_corruptors(corruptors: &[(String, usize)]) -> String {
    if corruptors.is_empty() {
        return "calls a delay or subroutine that may supersede it".to_string();
    }

    const MAX: usize = 3;
    let shown: Vec<String> = corruptors
        .iter()
        .take(MAX)
        .map(|(name, line)| {
            if *line > 0 {
                format!("`{}` at line {}", name, line)
            } else {
                format!("`{}`", name)
            }
        })
        .collect();

    let suffix = if corruptors.len() > MAX {
        format!(" (and {} more)", corruptors.len() - MAX)
    } else {
        String::new()
    };

    let joined = match shown.len() {
        1 => shown[0].clone(),
        2 => format!("{} and {}", shown[0], shown[1]),
        _ => {
            let head = shown[..shown.len() - 1].join(", ");
            format!("{}, and {}", head, shown[shown.len() - 1])
        }
    };

    format!("calls {}{} which may supersede it", joined, suffix)
}

/// The RuneScript parameter type to use when threading a `last_*` pointer
/// through as a label argument. Mirrors the return types declared on the
/// corresponding engine commands in `content/scripts/engine.rs2`:
///   last_useitem/last_item -> obj
///   last_com               -> component
///   last_useslot/last_slot/last_targetslot/last_int -> int
/// Every other static-only pointer falls back to `int` (safe default —
/// the suggestion lands in `Applicability::MaybeIncorrect` anyway).
fn pointer_param_type(ptr: PointerType) -> &'static str {
    use PointerType::*;
    match ptr {
        LastUseitem | LastItem => "obj",
        LastCom => "component",
        LastString => "string",
        LastCoord => "coord",
        _ => "int",
    }
}

/// Extract 1-indexed line `line_no` from `text`. `None` if out of range.
fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
    if line_no == 0 {
        return None;
    }
    text.lines().nth(line_no - 1)
}

/// Rewrite a caller line like `[oplocu,...] @label;` or
/// `@label(1);` to pass `last_useitem` (or whichever pointer) as an
/// additional argument. Returns `None` if the pattern isn't recognized.
///
/// Handles:
///   `@name;`                -> `@name(last_useitem);`
///   `@name(a, b);`          -> `@name(a, b, last_useitem);`
///   `~name;` / `~name(...)` (gosub) — same shape with `~`.
fn rewrite_call_site_arg(
    line: &str,
    arrow: &str,
    callee_short: &str,
    ptr_cmd: &str,
) -> Option<String> {
    // Locate `<arrow><callee_short>` as a call reference. The label may
    // appear multiple times on one line (rare) — we rewrite the first.
    let needle = format!("{}{}", arrow, callee_short);
    let start = line.find(&needle)?;
    let after_name = start + needle.len();
    let tail = &line[after_name..];

    // Case A: immediately followed by `;` or end-of-line — no existing args.
    let first_non_ws = tail.chars().next();
    if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
        || tail.trim_start().is_empty()
    {
        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
        out.push_str(&line[..after_name]);
        out.push('(');
        out.push_str(ptr_cmd);
        out.push(')');
        out.push_str(tail);
        return Some(out);
    }

    // Case B: followed by `(` — locate the matching `)` and insert the arg
    // just before it.
    if tail.trim_start().starts_with('(') {
        let open_rel = tail.find('(')?;
        let abs_open = after_name + open_rel;
        let close_rel = find_matching_close_paren(&line[abs_open..])?;
        let abs_close = abs_open + close_rel;

        // Empty arg list: `@name()` -> `@name(last_useitem)`.
        let inside = line[abs_open + 1..abs_close].trim();
        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
        out.push_str(&line[..abs_close]);
        if inside.is_empty() {
            out.push_str(ptr_cmd);
        } else {
            out.push_str(", ");
            out.push_str(ptr_cmd);
        }
        out.push_str(&line[abs_close..]);
        return Some(out);
    }

    None
}

/// Rewrite a label/proc header line to append `<ty> <name>` to its
/// parameter list. Handles all three forms:
///   `[label,foo]`              -> `[label,foo](obj $used)`
///   `[label,foo](int $x)`      -> `[label,foo](int $x, obj $used)`
///   `[proc,foo]()(int)`        -> `[proc,foo](obj $used)(int)`
fn rewrite_header_add_param(
    line: &str,
    callee_short: &str,
    param_type: &str,
    param_name: &str,
) -> Option<String> {
    // Locate the `,<callee_short>]` subject closer so we know where the
    // header ends and any parameter list begins.
    let needle = format!(",{}]", callee_short);
    let subject_end = line.find(&needle)?;
    let after_bracket = subject_end + needle.len();

    let remainder = &line[after_bracket..];
    let added = format!("{} {}", param_type, param_name);

    // No param list at all — append `(<ty> <name>)`.
    if !remainder.trim_start().starts_with('(') {
        let mut out = String::with_capacity(line.len() + added.len() + 2);
        out.push_str(&line[..after_bracket]);
        out.push('(');
        out.push_str(&added);
        out.push(')');
        out.push_str(remainder);
        return Some(out);
    }

    // Has at least one `(...)` — find its close and insert before it.
    let open_rel = remainder.find('(')?;
    let abs_open = after_bracket + open_rel;
    let close_rel = find_matching_close_paren(&line[abs_open..])?;
    let abs_close = abs_open + close_rel;
    let inside = line[abs_open + 1..abs_close].trim();

    let mut out = String::with_capacity(line.len() + added.len() + 2);
    out.push_str(&line[..abs_close]);
    if inside.is_empty() {
        out.push_str(&added);
    } else {
        out.push_str(", ");
        out.push_str(&added);
    }
    out.push_str(&line[abs_close..]);
    Some(out)
}

/// Locate the 1-indexed line that declares `[<trigger>,<name>]` in `src`.
/// Ignores leading whitespace; matches on the exact `[trigger,name]`
/// prefix (before any `(...)` parameter list).
fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
    let prefix = format!("[{},{}]", trigger, name);
    let prefix_with_params = format!("[{},{}](", trigger, name);
    for (i, line) in src.lines().enumerate() {
        let trimmed = line.trim_start();
        if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
            return Some(i + 1);
        }
    }
    None
}

/// Given a string whose first char is `(`, return the byte offset of the
/// matching `)`. Respects nesting but is deliberately naive about strings
/// (RuneScript headers don't contain string literals).
fn find_matching_close_paren(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    if bytes.first().copied() != Some(b'(') {
        return None;
    }
    let mut depth = 0i32;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Game-var Push/Pop instructions encode the secondary (dot-prefixed,
/// `.%v`) vs primary (`%v`) distinction in bit 16 of the integer operand
/// (see `compiler.rs` Expr::GameVar handling: `(1 << 16) | var_id`).
/// TS uses distinct opcodes for this; we collapse to a single opcode and
/// recover the flag here when attributing the pointer requirement.
fn is_secondary_var_operand(operand: &Operand) -> bool {
    match operand {
        Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
        _ => false,
    }
}

/// Resolve a jump target (an instruction index) to the CFG node index, walking
/// past any `LineNumber` instructions that are stripped from the CFG. Without
/// this, an `if` body's BranchEquals target — which usually lands on the body's
/// leading LineNumber — would fail the `instr_to_node.get()` lookup and the
/// edge would silently drop, disconnecting the body from its predecessors.
fn resolve_target_node(
    mut target_idx: usize,
    instructions: &[Instruction],
    instr_to_node: &HashMap<usize, usize>,
) -> Option<usize> {
    while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
        target_idx += 1;
    }
    instr_to_node.get(&target_idx).copied()
}

fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
    nodes[from].next.retain(|&n| n != to);
    nodes[to].previous.retain(|&n| n != from);
}

/// Find the source line number for an instruction by scanning backwards for
/// the nearest `LineNumber` instruction. Returns 0 if none found.
fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
    for i in (0..=instr_idx).rev() {
        if instructions[i].opcode == Opcode::LineNumber
            && let Operand::Int(line) = instructions[i].operand
        {
            return line as usize;
        }
    }
    0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
    use crate::symbol::SymbolRegistry;

    /// Build a minimal registry with a command registered at a given opcode.
    fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
        let mut reg = SymbolRegistry::new();
        for &(name, opcode) in commands {
            reg.register_command(name.to_string(), opcode, vec![], vec![]);
        }
        reg
    }

    /// Build a compiled script with the given trigger, name, and instructions.
    fn make_script(
        name: &str,
        trigger: &str,
        id: i32,
        instructions: Vec<Instruction>,
    ) -> CompiledScript {
        let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
        script.trigger = trigger.to_string();
        script.source_path = "test.rs2".to_string();
        script.instructions = instructions;
        script
    }

    /// Helper: Command instruction with encoded opcode (no secondary entity).
    fn cmd(opcode: i32) -> Instruction {
        Instruction::new(Opcode::Command, Operand::Int(opcode))
    }

    fn line(n: i32) -> Instruction {
        Instruction::new(Opcode::LineNumber, Operand::Int(n))
    }

    fn push_int(v: i32) -> Instruction {
        Instruction::push_int(v)
    }

    fn branch_eq(target: usize) -> Instruction {
        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
    }

    fn branch(target: usize) -> Instruction {
        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
    }

    fn ret() -> Instruction {
        Instruction::simple(Opcode::Return)
    }

    fn gosub(script_id: i32) -> Instruction {
        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
    }

    // -----------------------------------------------------------------------
    // Test: conditional setter with argument push between Command and Branch
    // -----------------------------------------------------------------------
    // Simulates: if (p_finduid(uid) = true) { p_stopaction; }
    // Bytecode: PushVar, Command(p_finduid), PushConstantInt(1), BranchEquals, Branch, ...
    // The conditional setter should be detected despite the PushVar before Command.
    #[test]
    fn conditional_setter_with_arg_push() {
        // p_finduid opcode = 4267 (arbitrary, just needs to be in command_pointers)
        // p_stopaction opcode = 4268
        let p_finduid_op = 4267;
        let p_stopaction_op = 4268;

        let registry = registry_with_commands(&[
            ("p_finduid", p_finduid_op),
            ("p_stopaction", p_stopaction_op),
        ]);

        let instructions = vec![
            line(1),              // 0: LineNumber
            push_int(0),          // 1: PushVar(uid) - simulated as push_int
            cmd(p_finduid_op),    // 2: Command(p_finduid)
            push_int(1),          // 3: PushConstantInt(1) = true
            branch_eq(7),         // 4: BranchEquals -> body
            branch(8),            // 5: Branch -> end
            line(2),              // 6: LineNumber
            cmd(p_stopaction_op), // 7: Command(p_stopaction) - requires p_active_player
            ret(),                // 8: Return
        ];

        // Script with "label" trigger (gets all pointers initially? No - we want
        // to test that the conditional setter provides the pointer)
        // Use "ai_timer" which only provides active_npc — no p_active_player.
        let script = make_script("test", "ai_timer", 0, instructions);
        let scripts = vec![script];

        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        // p_finduid conditionally sets p_active_player on the true branch.
        // p_stopaction requires p_active_player and is only on the true branch.
        // So this should produce NO diagnostics.
        assert_eq!(
            diags.warning_count(),
            0,
            "conditional setter should provide p_active_player on true branch, got {} warnings",
            diags.warning_count()
        );
    }

    #[test]
    fn boolean_branches_preserve_conditional_pointer_analysis() {
        let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
        for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
        {
            let script = make_script(
                "test",
                "ai_timer",
                0,
                vec![
                    line(1),
                    push_int(0),
                    cmd(4267),
                    Instruction::new(opcode, Operand::JumpTarget(target)),
                    branch(skip),
                    cmd(4268),
                    ret(),
                ],
            );
            assert_eq!(
                PointerChecker::new(&[script], &registry)
                    .run()
                    .warning_count(),
                0
            );
        }
        let script = make_script(
            "test",
            "ai_timer",
            0,
            vec![
                line(1),
                push_int(0),
                cmd(4267),
                Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
                branch(6),
                cmd(4268),
                ret(),
            ],
        );
        assert!(
            PointerChecker::new(&[script], &registry)
                .run()
                .warning_count()
                > 0
        );
    }

    // -----------------------------------------------------------------------
    // Test: proc that requires AND corrupts the same pointer (gnomeball pattern)
    // -----------------------------------------------------------------------
    // Simulates a label calling a proc that:
    //   - requires p_active_player (via p_delay)
    //   - then corrupts p_active_player (via npc_delay)
    // The Gosub node is simultaneously in required and corrupted lists.
    // This should NOT be flagged — the requirement is satisfied before corruption.
    #[test]
    fn gosub_requires_then_corrupts_same_pointer() {
        let p_delay_op = 5001;
        let npc_delay_op = 5002;

        let registry =
            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);

        // Proc: p_delay(0); npc_delay(0); return;
        // This proc requires p_active_player (p_delay) then corrupts it (npc_delay).
        let proc_script = make_script(
            "tackle_success",
            "proc",
            100,
            vec![
                line(1),
                push_int(0),
                cmd(p_delay_op), // requires p_active_player, does NOT corrupt it
                line(2),
                push_int(0),
                cmd(npc_delay_op), // corrupts p_active_player
                ret(),
            ],
        );

        // Label: calls the proc via gosub
        // The label trigger provides all pointers including p_active_player.
        let label_script = make_script(
            "do_tackle",
            "label",
            200,
            vec![
                line(10),
                gosub(100), // Gosub to proc — requires AND corrupts p_active_player
                ret(),
            ],
        );

        let scripts = vec![proc_script, label_script];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        // The label has p_active_player from trigger.
        // The gosub requires it (satisfied) then corrupts it.
        // No diagnostic — the main BFS starts from predecessors of the
        // required node (not the node itself), and the secondary require+
        // corrupt heuristic skips engine-tracked pointers like PActivePlayer.
        assert_eq!(
            diags.warning_count(),
            0,
            "gosub that requires-then-corrupts p_active_player should not \
             be flagged (engine-tracked pointer), got {} warnings",
            diags.warning_count()
        );
    }

    // -----------------------------------------------------------------------
    // Test: legitimate corruption SHOULD be caught
    // -----------------------------------------------------------------------
    // A command corrupts p_active_player, then a later command requires it.
    // This should produce an error.
    #[test]
    fn corruption_before_requirement_is_caught() {
        let npc_delay_op = 5002;
        let p_delay_op = 5001;

        let registry =
            registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);

        // Label: npc_delay(0); p_delay(0);
        // npc_delay corrupts p_active_player, then p_delay requires it.
        let script = make_script(
            "bad_order",
            "label",
            0,
            vec![
                line(1),
                push_int(0),
                cmd(npc_delay_op), // corrupts p_active_player
                line(2),
                push_int(0),
                cmd(p_delay_op), // requires p_active_player — should fail!
                ret(),
            ],
        );

        let scripts = vec![script];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        assert!(
            diags.warning_count() > 0,
            "corruption before requirement should be caught as a warning"
        );
    }

    // -----------------------------------------------------------------------
    // Test: uninitialized pointer access
    // -----------------------------------------------------------------------
    // A script with a trigger that doesn't provide p_active_player uses p_delay.
    #[test]
    fn uninitialized_pointer_caught() {
        let p_delay_op = 5001;

        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);

        // ai_timer trigger only provides active_npc, not p_active_player.
        let script = make_script(
            "bad_access",
            "ai_timer",
            0,
            vec![
                line(1),
                push_int(0),
                cmd(p_delay_op), // requires p_active_player — not provided by trigger
                ret(),
            ],
        );

        let scripts = vec![script];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        assert!(
            diags.warning_count() > 0,
            "uninitialized pointer access should be caught"
        );
    }

    // -----------------------------------------------------------------------
    // Test: region pointers
    // -----------------------------------------------------------------------
    // A region command needs a region the script created or found, and its
    // dot form the secondary one.
    #[test]
    fn region_commands_need_their_region() {
        let (create, set) = (5202, 5203);
        let registry = registry_with_commands(&[("region_create", create), ("region_set", set)]);
        let dot = |opcode: i32| opcode | (1 << 16);
        let warnings = |instructions: Vec<Instruction>| {
            let scripts = vec![make_script("test", "ai_timer", 0, instructions)];
            PointerChecker::new(&scripts, &registry)
                .run()
                .warning_count()
        };
        assert_eq!(
            warnings(vec![line(1), cmd(create), line(2), cmd(set), ret()]),
            0
        );
        assert!(warnings(vec![line(1), cmd(set), ret()]) > 0);
        assert!(warnings(vec![line(1), cmd(create), line(2), cmd(dot(set)), ret()]) > 0);
        assert_eq!(
            warnings(vec![
                line(1),
                cmd(dot(create)),
                line(2),
                cmd(dot(set)),
                ret()
            ]),
            0
        );
    }

    // -----------------------------------------------------------------------
    // Test: jump target landing on a LineNumber instruction
    // -----------------------------------------------------------------------
    // Regression: BranchEquals/Branch targets patched to body_start often
    // land on a LineNumber instruction (emitted for the body's first source
    // line). LineNumbers are stripped from the CFG, so without
    // resolve_target_node() the edge would be silently dropped and the body
    // node would have no predecessors — hiding genuine uninitialized-pointer
    // errors for callers that wrap the @jump in an `if` block.
    #[test]
    fn branch_target_on_line_number_still_connects() {
        let p_delay_op = 5001;
        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);

        // ai_timer trigger provides active_npc but NOT p_active_player.
        // Layout: `if (1 = 1) { p_delay(0); }` — BranchEquals jumps to the
        // body's leading LineNumber. If the CFG drops that edge the body
        // node is disconnected and the uninitialized p_active_player read
        // is never flagged.
        //
        //   0 LineNumber(1)
        //   1 PushConstantInt(1)
        //   2 PushConstantInt(1)
        //   3 BranchEquals -> 5 (LineNumber at body start)
        //   4 Branch       -> 8 (end-of-if marker; here, Return)
        //   5 LineNumber(2)
        //   6 PushConstantInt(0)
        //   7 Command(p_delay)
        //   8 Return
        let script = make_script(
            "target_on_line_number",
            "ai_timer",
            0,
            vec![
                line(1),
                push_int(1),
                push_int(1),
                branch_eq(5), // jump target is the LineNumber at index 5
                Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
                line(2),
                push_int(0),
                cmd(p_delay_op),
                ret(),
            ],
        );

        let scripts = vec![script];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        assert!(
            diags.warning_count() > 0,
            "jump target on LineNumber must still flag uninitialized pointer \
             access (got {} warnings)",
            diags.warning_count()
        );
    }

    // -----------------------------------------------------------------------
    // Test: secondary require+corrupt warning for static-only pointers
    // -----------------------------------------------------------------------
    // A label that requires AND corrupts LastUseitem (via last_useitem then
    // p_delay) is called via @jump from an oplocu trigger that provides
    // LastUseitem. The main BFS correctly finds no error (predecessors are
    // clean), but the secondary heuristic flags the Jump as "requires and
    // corrupts last_useitem on the same node" — this is the 23-warning
    // pattern from the legacy lost-city 225 output.
    #[test]
    fn secondary_requires_and_corrupts_warns_for_static_pointer() {
        // last_useitem and p_delay opcodes (arbitrary, just need to be in
        // command_pointers()).
        let last_useitem_op = 4270;
        let p_delay_op = 5001;
        let registry =
            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);

        // Callee label: reads last_useitem, then corrupts it via p_delay.
        let callee = make_script(
            "consume_useitem",
            "label",
            100,
            vec![
                line(1),
                cmd(last_useitem_op), // requires LastUseitem
                line(2),
                push_int(0),
                cmd(p_delay_op), // corrupts LastUseitem
                ret(),
            ],
        );

        // Caller: oplocu trigger provides LastUseitem. Jumps to the label.
        // The Jump node inherits BOTH required[LastUseitem] AND
        // corrupted[LastUseitem]. Main BFS: predecessors of Jump trace back
        // to node 0, which is NOT corrupted (trigger provides) — no main
        // diagnostic. Secondary heuristic: Jump appears in both sets, emit
        // a warning.
        let caller = make_script(
            "use_on_loc",
            "oplocu",
            200,
            vec![
                line(10),
                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
            ],
        );

        let scripts = vec![callee, caller];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        let last_useitem_warnings = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("last_useitem"))
            .count();
        assert!(
            last_useitem_warnings > 0,
            "static-only pointer (last_useitem) should trigger the \
             require+corrupt warning at the jump site; got diags: {:?}",
            diags
                .diagnostics()
                .iter()
                .map(|d| &d.message)
                .collect::<Vec<_>>()
        );

        assert_eq!(
            diags.error_count(),
            0,
            "pointer-check diagnostics must never raise error severity; got {} errors",
            diags.error_count()
        );
    }

    // -----------------------------------------------------------------------
    // Test: secondary heuristic SUPPRESSES warnings for engine-tracked pointers
    // -----------------------------------------------------------------------
    // Same pattern as above, but the pointer is PActivePlayer (engine-
    // tracked). The secondary heuristic must NOT emit — the user's legacy
    // 23-warning output specifically excludes the gnome_baller
    // p_active_player findings because the 2004scape engine manages that
    // pointer at runtime.
    #[test]
    fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
        let p_delay_op = 5001;
        let npc_delay_op = 5002;
        let registry =
            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);

        let callee = make_script(
            "consume_protected",
            "proc",
            100,
            vec![
                line(1),
                push_int(0),
                cmd(p_delay_op), // requires PActivePlayer
                line(2),
                push_int(0),
                cmd(npc_delay_op), // corrupts PActivePlayer
                ret(),
            ],
        );

        // opnpc1 provides ActivePlayer, PActivePlayer, ActiveNpc.
        let caller = make_script(
            "do_opnpc",
            "opnpc1",
            200,
            vec![
                line(10),
                Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
                ret(),
            ],
        );

        let scripts = vec![callee, caller];
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        let p_active_player_warnings = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("p_active_player"))
            .count();
        assert_eq!(
            p_active_player_warnings, 0,
            "engine-tracked pointer (p_active_player) must not trigger the \
             require+corrupt warning; got {} such warnings",
            p_active_player_warnings
        );
    }

    // -----------------------------------------------------------------------
    // Test: secondary (dot-prefixed) var reads require the `*2` pointer
    // -----------------------------------------------------------------------
    // Regression: categorize_nodes used to map every PushVarn/PopVarn (and
    // PushVarp/PopVarp/PushVarpBit/PopVarpBit) to the primary active_npc /
    // active_player pointer, ignoring the bit-16 "secondary" flag that
    // compiler.rs sets on `.%var` operands. That miscategorization caused
    // the 4 spurious `uninitialized active_npc` warnings at
    // gnomeball_pass.rs2:1,2 and duel_arena.rs2:3,10.
    //
    // A proc reading `.%npc_var` should only require active_npc2 — no
    // active_npc warning should propagate to its callers.
    #[test]
    fn secondary_varn_requires_active_npc2_not_primary() {
        // PushVarn is Opcode::PushVarn (=4). Operand encodes var_id in low
        // 16 bits; bit 16 marks secondary. We bypass the varn registry by
        // emitting the raw opcode — the pointer checker only inspects the
        // opcode + operand.
        let secondary_varn = Instruction::new(
            Opcode::PushVarn,
            Operand::Int(1 << 16), // .%var_id 0, secondary
        );

        // Proc reads a secondary NPC var and returns.
        let proc_script = make_script(
            "reads_secondary_varn",
            "proc",
            100,
            vec![
                line(1),
                secondary_varn,
                Instruction::simple(Opcode::PopIntDiscard),
                ret(),
            ],
        );

        // Caller: opplayer1 trigger provides active_player/p_active_player/
        // active_player2, but does NOT provide active_npc or active_npc2.
        // Before the fix, the gosub inherited active_npc (primary) from the
        // proc and the caller would be flagged "uninitialized active_npc".
        // After the fix, the proc only requires active_npc2, which also
        // isn't provided — but crucially, `active_npc` is not flagged.
        let caller = make_script(
            "gosub_into_proc",
            "opplayer1",
            200,
            vec![line(10), gosub(100), ret()],
        );

        let scripts = vec![proc_script, caller];
        let registry = registry_with_commands(&[]);
        let mut checker = PointerChecker::new(&scripts, &registry);
        let diags = checker.run();

        // Diagnostic messages use the pointer's `representation()`:
        //   PointerType::ActiveNpc  -> "active_npc"
        //   PointerType::ActiveNpc2 -> ".active_npc"
        // Match "pointer active_npc." to count ONLY primary hits — the
        // secondary form appears as "pointer .active_npc.".
        let active_npc_primary_warnings = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("pointer active_npc."))
            .count();
        assert_eq!(
            active_npc_primary_warnings,
            0,
            "secondary .%var read must not flag primary active_npc at the \
             caller; got diags: {:?}",
            diags
                .diagnostics()
                .iter()
                .filter(|d| d.severity == Severity::Warning)
                .map(|d| &d.message)
                .collect::<Vec<_>>()
        );

        // Sanity: the secondary requirement DID propagate — opplayer1 doesn't
        // provide active_npc2 either, so `.active_npc` should be flagged.
        // This proves the attribution went to the `*2` pointer as intended.
        let active_npc2_warnings = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("pointer .active_npc."))
            .count();
        assert!(
            active_npc2_warnings > 0,
            "secondary .%var should route the requirement to active_npc2; \
             got no such warning"
        );
    }

    // -----------------------------------------------------------------------
    // Unit tests for the Rule A text rewriters
    // -----------------------------------------------------------------------

    #[test]
    fn rewrite_call_site_no_args() {
        let got = rewrite_call_site_arg(
            "[opnpcu,wantcat1] @civilian_give_runes;",
            "@",
            "civilian_give_runes",
            "last_useitem",
        )
        .unwrap();
        assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
    }

    #[test]
    fn rewrite_call_site_with_args() {
        let got = rewrite_call_site_arg(
            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
            "@",
            "amulet_of_glory_interface",
            "last_item",
        )
        .unwrap();
        assert_eq!(
            got,
            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
        );
    }

    #[test]
    fn rewrite_call_site_gosub_no_args() {
        let got =
            rewrite_call_site_arg("    ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
        assert_eq!(got, "    ~some_proc(last_useitem);");
    }

    #[test]
    fn rewrite_call_site_empty_arg_list() {
        let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
        assert_eq!(got, "@foo(last_useitem);");
    }

    #[test]
    fn rewrite_header_no_params() {
        let got = rewrite_header_add_param(
            "[label,civilian_give_runes]",
            "civilian_give_runes",
            "obj",
            "$last_useitem",
        )
        .unwrap();
        assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
    }

    #[test]
    fn rewrite_header_with_existing_params() {
        let got = rewrite_header_add_param(
            "[label,amulet_of_glory_interface](string $message)",
            "amulet_of_glory_interface",
            "obj",
            "$last_item",
        )
        .unwrap();
        assert_eq!(
            got,
            "[label,amulet_of_glory_interface](string $message, obj $last_item)"
        );
    }

    #[test]
    fn rewrite_header_proc_with_return_type() {
        // `[proc,foo]()(int)` — parameter list comes before the return
        // list. We must insert into the FIRST `(...)` group.
        let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
        assert_eq!(got, "[proc,foo](obj $x)(int)");
    }

    #[test]
    fn find_header_line_matches_trigger_and_name() {
        let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
        assert_eq!(find_header_line(src, "label", "foo"), Some(2));
        assert_eq!(find_header_line(src, "label", "bar"), Some(4));
        assert_eq!(find_header_line(src, "label", "missing"), None);
    }

    #[test]
    fn format_corruptors_shapes() {
        assert_eq!(
            format_corruptors(&[]),
            "calls a delay or subroutine that may supersede it"
        );
        assert_eq!(
            format_corruptors(&[("p_delay".to_string(), 21)]),
            "calls `p_delay` at line 21 which may supersede it"
        );
        assert_eq!(
            format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
            "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
        );
        assert_eq!(
            format_corruptors(&[
                ("p_delay".to_string(), 21),
                ("~chatnpc".to_string(), 11),
                ("~objbox".to_string(), 14),
            ]),
            "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
        );
        // Truncates after 3 with a summary suffix.
        assert_eq!(
            format_corruptors(&[
                ("p_delay".to_string(), 1),
                ("~a".to_string(), 2),
                ("~b".to_string(), 3),
                ("~c".to_string(), 4),
                ("~d".to_string(), 5),
            ]),
            "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
        );
        // Unknown line falls back to bare name.
        assert_eq!(
            format_corruptors(&[("p_delay".to_string(), 0)]),
            "calls `p_delay` which may supersede it"
        );
    }

    #[test]
    fn find_matching_close_paren_nested() {
        assert_eq!(find_matching_close_paren("()"), Some(1));
        assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
        assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
        assert_eq!(find_matching_close_paren("("), None);
        assert_eq!(find_matching_close_paren("abc"), None);
    }

    // -----------------------------------------------------------------------
    // Test: secondary require+corrupt warning carries a populated Help
    //       with concrete before/after suggestions when source is available
    // -----------------------------------------------------------------------
    #[test]
    fn secondary_warning_attaches_help_with_rewrite_suggestions() {
        use std::collections::HashMap;
        use std::sync::Arc;

        let last_useitem_op = 4270;
        let p_delay_op = 5001;
        let registry =
            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);

        // Callee label — reads last_useitem, then p_delay corrupts it.
        let mut callee = make_script(
            "consume_useitem",
            "label",
            100,
            vec![
                line(2), // body starts on source line 2
                cmd(last_useitem_op),
                line(3),
                push_int(0),
                cmd(p_delay_op),
                ret(),
            ],
        );
        callee.source_path = "/virt/consume.rs2".to_string();

        // Caller — oplocu provides last_useitem; @jumps into callee.
        let mut caller = make_script(
            "use_on_loc",
            "oplocu",
            200,
            vec![
                line(1),
                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
            ],
        );
        caller.source_path = "/virt/caller.rs2".to_string();

        // Virtual source text. Caller on line 1, callee header on line 1
        // of its own file.
        let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
        source_cache.insert(
            "/virt/caller.rs2".to_string(),
            Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
        );
        source_cache.insert(
            "/virt/consume.rs2".to_string(),
            Arc::new(
                "[label,consume_useitem]\n\
                 last_useitem;\n\
                 p_delay(0);\n"
                    .to_string(),
            ),
        );

        let scripts = vec![callee, caller];
        let mut checker = PointerChecker::new(&scripts, &registry);
        checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
        let diags = checker.run();

        // Find the corrupted-last_useitem warning and verify help is
        // attached with both call-site and header rewrites.
        let warning = diags
            .diagnostics()
            .iter()
            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
            .expect("expected a stale-last_useitem warning");

        assert_eq!(
            warning.help.len(),
            1,
            "warning should have exactly one Help block, got {}",
            warning.help.len()
        );
        let help = &warning.help[0];
        assert!(
            help.message.contains("consume_useitem"),
            "help message should name the callee, got: {}",
            help.message
        );
        assert!(
            help.message.contains("last_useitem"),
            "help message should name the pointer, got: {}",
            help.message
        );

        // Two suggestions: (1) call site, (2) label header.
        assert_eq!(
            help.suggestions.len(),
            2,
            "help should include both call-site and header suggestions, \
             got {}: {:?}",
            help.suggestions.len(),
            help.suggestions
                .iter()
                .map(|s| &s.label)
                .collect::<Vec<_>>()
        );

        // Caller rewrite lands on the call file.
        let caller_sug = help
            .suggestions
            .iter()
            .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
            .expect("expected a call-site suggestion on the caller file");
        assert!(
            caller_sug
                .replacement
                .contains("@consume_useitem(last_useitem)"),
            "call-site replacement must pass last_useitem as an arg, got: {}",
            caller_sug.replacement
        );

        // Header rewrite lands on the callee file.
        let header_sug = help
            .suggestions
            .iter()
            .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
            .expect("expected a header suggestion on the callee file");
        assert!(
            header_sug.replacement.contains("(obj $last_useitem)"),
            "header replacement must add `obj $last_useitem` param, got: {}",
            header_sug.replacement
        );

        assert_eq!(help.applicability, Applicability::MaybeIncorrect);
    }

    // -----------------------------------------------------------------------
    // Test: help falls back to prose-only when source cache is absent
    // -----------------------------------------------------------------------
    #[test]
    fn secondary_warning_falls_back_to_prose_help_without_source() {
        let last_useitem_op = 4270;
        let p_delay_op = 5001;
        let registry =
            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);

        let callee = make_script(
            "consume_useitem",
            "label",
            100,
            vec![
                line(1),
                cmd(last_useitem_op),
                line(2),
                push_int(0),
                cmd(p_delay_op),
                ret(),
            ],
        );
        let caller = make_script(
            "use_on_loc",
            "oplocu",
            200,
            vec![
                line(1),
                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
            ],
        );

        let scripts = vec![callee, caller];
        let mut checker = PointerChecker::new(&scripts, &registry);
        // Deliberately NO set_source_cache call.
        let diags = checker.run();

        let warning = diags
            .diagnostics()
            .iter()
            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
            .expect("warning still fires without source cache");

        assert_eq!(warning.help.len(), 1);
        let help = &warning.help[0];
        assert_eq!(
            help.suggestions.len(),
            0,
            "prose-only help should have no concrete suggestions"
        );
        assert_eq!(help.applicability, Applicability::Unspecified);
    }
}