ghostscope-compiler 0.1.5

Compiles GhostScope trace definitions into DWARF-aware eBPF programs ready for injection.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
use pest::iterators::{Pair, Pairs};
use pest::Parser;
use pest::RuleType;
use pest_derive::Parser;

use crate::script::ast::{
    infer_type, BacktraceStatement, BinaryOp, Expr, PrintStatement, Program, Statement,
    TracePattern,
};
use crate::script::format_validator::FormatValidator;
use tracing::{debug, info};

#[derive(Parser)]
#[grammar = "script/grammar.pest"]
pub struct GhostScopeParser;

#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    #[error("Pest parser error: {0}")]
    Pest(#[from] Box<pest::error::Error<Rule>>),

    #[error("Unexpected token: {0:?}")]
    UnexpectedToken(Rule),

    #[error("Invalid expression")]
    InvalidExpression,

    #[error("Syntax error: {0}")]
    SyntaxError(String),

    #[error("Type error: {0}")]
    TypeError(String),

    #[error("Unsupported feature: {0}")]
    UnsupportedFeature(String),
}

impl From<pest::error::Error<Rule>> for ParseError {
    fn from(err: pest::error::Error<Rule>) -> Self {
        ParseError::Pest(Box::new(err))
    }
}

pub type Result<T> = std::result::Result<T, ParseError>;

// Custom chunks function with RuleType constraint
fn chunks_of_two<'a, T: RuleType>(pairs: Pairs<'a, T>) -> Vec<Vec<Pair<'a, T>>> {
    let pairs_vec: Vec<_> = pairs.collect();
    let mut result = Vec::new();

    let mut i = 0;
    // Only produce full (op, rhs) pairs; ignore any trailing leftover defensively
    while i + 1 < pairs_vec.len() {
        result.push(vec![pairs_vec[i].clone(), pairs_vec[i + 1].clone()]);
        i += 2;
    }

    result
}

pub fn parse(input: &str) -> Result<Program> {
    debug!("Starting to parse input: {}", input.trim());

    let pairs = match GhostScopeParser::parse(Rule::program, input) {
        Ok(p) => p,
        Err(e) => {
            // Heuristic: detect unclosed string in print lines to provide a clearer hint
            if let Some(msg) = detect_unclosed_print_string(input) {
                return Err(ParseError::SyntaxError(msg));
            }
            if let Some(msg) = detect_backtrace_depth_argument(input) {
                return Err(ParseError::SyntaxError(msg));
            }
            // Heuristic: detect likely misspelled or unknown keywords and suggest fixes
            if let Some(msg) = detect_unknown_keyword(input) {
                return Err(ParseError::SyntaxError(msg));
            }
            return Err(ParseError::Pest(Box::new(e)));
        }
    };
    let mut program = Program::new();

    for pair in pairs {
        debug!(
            "Parsing top-level rule: {:?} = '{}'",
            pair.as_rule(),
            pair.as_str().trim()
        );
        match pair.as_rule() {
            Rule::statement => {
                let statement = parse_statement(pair)?;
                program.add_statement(statement);
            }
            Rule::EOI => {}
            _ => return Err(ParseError::UnexpectedToken(pair.as_rule())),
        }
    }

    debug!("Parsing completed successfully");
    Ok(program)
}

// Best-effort heuristic: if a line contains a print statement with an opening quote
// but no closing quote before arguments, give a clearer error.
fn detect_unclosed_print_string(input: &str) -> Option<String> {
    for (i, raw_line) in input.lines().enumerate() {
        let line = raw_line.trim_start();
        if !line.contains("print ") && !line.starts_with("print") {
            continue;
        }
        // Toggle on '"' to detect unclosed string; ignore escaped quotes for simplicity
        let mut open = false;
        for ch in line.chars() {
            if ch == '"' {
                open = !open;
            }
        }
        if open {
            // Common case: missing closing quote before comma and arguments
            if line.contains(',') {
                return Some(format!(
                    "Unclosed string literal in print at line {}. Did you forget a closing \"\" before ',' and arguments?",
                    i + 1
                ));
            } else {
                return Some(format!(
                    "Unclosed string literal in print at line {}.",
                    i + 1
                ));
            }
        }
    }
    None
}

fn detect_backtrace_depth_argument(input: &str) -> Option<String> {
    fn boundary_before(line: &str, idx: usize) -> bool {
        idx == 0
            || line[..idx]
                .chars()
                .next_back()
                .is_some_and(|ch| ch.is_whitespace() || matches!(ch, '{' | ';' | '}'))
    }

    for (line_idx, raw_line) in input.lines().enumerate() {
        let line = raw_line.split("//").next().unwrap_or(raw_line);
        for command in ["bt", "backtrace"] {
            for (idx, _) in line.match_indices(command) {
                if !boundary_before(line, idx) {
                    continue;
                }
                let after = &line[idx + command.len()..];
                if !after.starts_with(char::is_whitespace) {
                    continue;
                }
                let arg = after.trim_start();
                if arg.starts_with("depth")
                    || arg.chars().next().is_some_and(|ch| ch.is_ascii_digit())
                {
                    return Some(format!(
                        "bt depth is no longer a script option at line {}. Set the global limit with --backtrace-depth <N> or [ebpf] backtrace_depth = N.",
                        line_idx + 1
                    ));
                }
            }
        }
    }
    None
}

// Try to detect lines that start with an unknown/misspelled keyword and suggest known ones.
fn detect_unknown_keyword(input: &str) -> Option<String> {
    // Suggest only currently supported top-level keywords.
    const SUGGEST: &[&str] = &["trace", "print", "if", "else", "let"];
    // Valid statement starters that should not be flagged as unknown
    const SUPPORTED_HEADS: &[&str] = &["trace", "print", "if", "else", "let", "backtrace", "bt"];
    // Builtin call names allowed at expression head
    const BUILTIN_CALLS: &[&str] = &["memcmp", "strncmp", "starts_with", "hex", "cast"];

    // Helper: simple Levenshtein distance (small strings, few keywords)
    fn levenshtein(a: &str, b: &str) -> usize {
        let (n, m) = (a.len(), b.len());
        let mut dp = vec![0usize; (n + 1) * (m + 1)];
        let idx = |i: usize, j: usize| i * (m + 1) + j;
        for i in 0..=n {
            dp[idx(i, 0)] = i;
        }
        for j in 0..=m {
            dp[idx(0, j)] = j;
        }
        let ac: Vec<char> = a.chars().collect();
        let bc: Vec<char> = b.chars().collect();
        for i in 1..=n {
            for j in 1..=m {
                let cost = if ac[i - 1] == bc[j - 1] { 0 } else { 1 };
                let del = dp[idx(i - 1, j)] + 1;
                let ins = dp[idx(i, j - 1)] + 1;
                let sub = dp[idx(i - 1, j - 1)] + cost;
                dp[idx(i, j)] = del.min(ins).min(sub);
            }
        }
        dp[idx(n, m)]
    }

    // Helper: check a slice for a command-like unknown keyword
    fn check_slice(slice: &str, line_no_1based: usize) -> Option<String> {
        let mut s = slice.trim_start();
        if s.is_empty() || s.starts_with("//") {
            return None;
        }

        // If this slice begins with an if/else-if header, jump inside the condition
        if let Some(rest) = s.strip_prefix("if") {
            if rest.starts_with(char::is_whitespace) {
                s = rest.trim_start();
            }
        } else if let Some(rest) = s.strip_prefix("else") {
            let rest = rest.trim_start();
            if let Some(rest2) = rest.strip_prefix("if") {
                if rest2.starts_with(char::is_whitespace) {
                    s = rest2.trim_start();
                }
            } else {
                // 'else { ... }' — nothing to inspect here
            }
        }
        // Keywords must start with a letter or underscore; skip numeric heads
        let mut iter = s.chars();
        let first = iter.next()?;
        if !(first.is_ascii_alphabetic() || first == '_') {
            return None;
        }
        let mut token = String::new();
        token.push(first);
        for ch in iter {
            if ch.is_ascii_alphanumeric() || ch == '_' {
                token.push(ch);
            } else {
                break;
            }
        }
        if token.is_empty() {
            return None;
        }
        if SUPPORTED_HEADS.iter().any(|k| *k == token) {
            return None;
        }
        let rest_untrimmed = &s[token.len()..];
        let rest = rest_untrimmed.trim_start();
        if rest.starts_with('=') || rest.starts_with('[') || rest.starts_with('.') {
            // likely an expression starting with identifier
            return None;
        }
        // Allow builtin calls as expression statements
        if BUILTIN_CALLS.iter().any(|k| *k == token) && rest.starts_with('(') {
            return None;
        }
        if rest.starts_with('(')
            || rest.starts_with('{')
            || rest.starts_with('"')
            || rest_untrimmed.starts_with(char::is_whitespace)
        {
            // If it looks like a call (token + '('), include builtin calls in suggestion candidates
            let candidates: Vec<&str> = if rest.starts_with('(') {
                let mut v = Vec::new();
                v.extend_from_slice(SUGGEST);
                v.extend_from_slice(BUILTIN_CALLS);
                v
            } else {
                SUGGEST.to_vec()
            };
            let mut suggestions: Vec<(&str, usize)> = candidates
                .iter()
                .map(|&k| (k, levenshtein(&token, k)))
                .collect();
            suggestions.sort_by_key(|&(_, d)| d);
            if let Some((cand, dist)) = suggestions.first().copied() {
                if dist <= 2 {
                    return Some(format!(
                        "Unknown keyword '{token}' at line {line_no_1based}. Did you mean '{cand}'?"
                    ));
                }
            }
            return Some(format!(
                "Unknown keyword '{token}' at line {}. Expected one of: {}",
                line_no_1based,
                SUGGEST.join(", ")
            ));
        }
        None
    }

    for (i, raw_line) in input.lines().enumerate() {
        let line = raw_line;
        // Scan potential statement starts: at line start, and right after '{', ';', '}', '(', ',' (outside strings)
        let mut quote_open = false;
        let mut positions: Vec<usize> = vec![0]; // include start-of-line
        for (idx, ch) in line.char_indices() {
            if ch == '"' {
                quote_open = !quote_open;
            }
            if !quote_open && (ch == '{' || ch == ';' || ch == '}' || ch == '(' || ch == ',') {
                let next = idx + ch.len_utf8();
                if next < line.len() {
                    positions.push(next);
                }
            }
        }
        for &pos in &positions {
            if let Some(msg) = check_slice(&line[pos..], i + 1) {
                return Some(msg);
            }
        }
    }
    None
}

fn parse_backtrace_stmt(pair: Pair<Rule>) -> Result<BacktraceStatement> {
    let mut stmt = BacktraceStatement::default();

    for arg in pair.into_inner() {
        if arg.as_rule() == Rule::backtrace_flag {
            match arg.as_str() {
                "raw" => stmt.raw = true,
                "full" => stmt.full = true,
                "inline" => stmt.inline = true,
                "noinline" => stmt.inline = false,
                other => {
                    return Err(ParseError::SyntaxError(format!(
                        "Unknown bt option '{other}'"
                    )))
                }
            }
        }
    }

    Ok(stmt)
}

fn parse_statement(pair: Pair<Rule>) -> Result<Statement> {
    debug!(
        "parse_statement: {:?} = '{}'",
        pair.as_rule(),
        pair.as_str().trim()
    );
    let inner = pair
        .into_inner()
        .next()
        .ok_or(ParseError::InvalidExpression)?;
    debug!(
        "parse_statement inner: {:?} = '{}'",
        inner.as_rule(),
        inner.as_str().trim()
    );

    match inner.as_rule() {
        Rule::trace_stmt => {
            let mut inner_pairs = inner.into_inner();
            let pattern_pair = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
            let pattern = parse_trace_pattern(pattern_pair)?;

            let mut body = Vec::new();
            for stmt_pair in inner_pairs {
                // Disallow nested trace statements (trace is top-level only)
                if stmt_pair.as_rule() == Rule::statement {
                    let mut peek = stmt_pair.clone().into_inner();
                    if let Some(first) = peek.next() {
                        if first.as_rule() == Rule::trace_stmt {
                            return Err(ParseError::SyntaxError(
                                "'trace' cannot be nested; it is only allowed at the top level"
                                    .to_string(),
                            ));
                        }
                    }
                }
                let stmt = parse_statement(stmt_pair)?;
                body.push(stmt);
            }

            Ok(Statement::TracePoint { pattern, body })
        }
        Rule::print_stmt => {
            let print_content = inner
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            let print_stmt = parse_print_content(print_content)?;
            Ok(Statement::Print(print_stmt))
        }
        Rule::backtrace_stmt => Ok(Statement::Backtrace(parse_backtrace_stmt(inner)?)),
        Rule::assign_stmt => {
            // Friendly error for immutable variables (no assignment supported)
            let mut it = inner.into_inner();
            let name = it
                .next()
                .ok_or(ParseError::InvalidExpression)?
                .as_str()
                .to_string();
            // consume rhs expr
            let _ = it.next();
            Err(ParseError::TypeError(format!(
                "Assignment is not supported: variables are immutable. Use 'let {name} = ...' to bind once."
            )))
        }
        Rule::expr_stmt => {
            let expr = inner
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            let parsed_expr = parse_expr(expr)?;

            // Check expression type to ensure consistent operation types
            if let Err(err) = infer_type(&parsed_expr) {
                return Err(ParseError::TypeError(err));
            }

            Ok(Statement::Expr(parsed_expr))
        }
        Rule::var_decl_stmt => {
            let mut inner_pairs = inner.into_inner();
            let name = inner_pairs
                .next()
                .ok_or(ParseError::InvalidExpression)?
                .as_str()
                .to_string();
            let expr = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
            let parsed_expr = parse_expr(expr)?;

            // Check expression type to ensure consistent operation types
            if let Err(err) = infer_type(&parsed_expr) {
                return Err(ParseError::TypeError(err));
            }

            if is_alias_expr(&parsed_expr) {
                Ok(Statement::AliasDeclaration {
                    name,
                    target: parsed_expr,
                })
            } else {
                Ok(Statement::VarDeclaration {
                    name,
                    value: parsed_expr,
                })
            }
        }
        Rule::if_stmt => {
            debug!("Parsing if_stmt");
            let mut inner_pairs = inner.into_inner();
            let condition_pair = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
            debug!(
                "if_stmt condition_pair: {:?} = '{}'",
                condition_pair.as_rule(),
                condition_pair.as_str().trim()
            );
            let condition = parse_condition(condition_pair)?;

            // Parse then body statements
            let mut then_body = Vec::new();
            let mut else_body = None;

            for pair in inner_pairs {
                match pair.as_rule() {
                    Rule::statement => {
                        then_body.push(parse_statement(pair)?);
                    }
                    Rule::else_clause => {
                        else_body = Some(Box::new(parse_else_clause(pair)?));
                        break;
                    }
                    _ => return Err(ParseError::UnexpectedToken(pair.as_rule())),
                }
            }

            Ok(Statement::If {
                condition,
                then_body,
                else_body,
            })
        }
        _ => Err(ParseError::UnexpectedToken(inner.as_rule())),
    }
}

fn parse_expr(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::expr => {
            let inner = pair
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            parse_logical_or(inner)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

/// Determine if an expression should be treated as a DWARF alias binding.
/// This is a purely syntactic check (parser phase) and does not consult DWARF.
fn integer_literal_value(e: &Expr) -> Option<i64> {
    use crate::script::ast::BinaryOp as BO;
    use crate::script::ast::Expr as E;

    match e {
        E::Int(value) => Some(*value),
        E::BinaryOp {
            left,
            op: BO::Add,
            right,
        } => integer_literal_value(left)?.checked_add(integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::Subtract,
            right,
        } => integer_literal_value(left)?.checked_sub(integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::Multiply,
            right,
        } => integer_literal_value(left)?.checked_mul(integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::Divide,
            right,
        } => integer_literal_value(left)?.checked_div(integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::Modulo,
            right,
        } => integer_literal_value(left)?.checked_rem(integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::BitAnd,
            right,
        } => Some(integer_literal_value(left)? & integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::BitXor,
            right,
        } => Some(integer_literal_value(left)? ^ integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::BitOr,
            right,
        } => Some(integer_literal_value(left)? | integer_literal_value(right)?),
        E::BinaryOp {
            left,
            op: BO::ShiftLeft,
            right,
        } => {
            let shift = u32::try_from(integer_literal_value(right)?).ok()?;
            integer_literal_value(left)?.checked_shl(shift)
        }
        E::BinaryOp {
            left,
            op: BO::ShiftRight,
            right,
        } => {
            let shift = u32::try_from(integer_literal_value(right)?).ok()?;
            integer_literal_value(left)?.checked_shr(shift)
        }
        E::UnaryBitNot(inner) => Some(!integer_literal_value(inner)?),
        _ => None,
    }
}

fn is_alias_expr(e: &Expr) -> bool {
    use crate::script::ast::BinaryOp as BO;
    use crate::script::ast::Expr as E;
    match e {
        E::AddressOf(_) => true,
        // Constant offset on top of an alias-eligible expression
        E::BinaryOp {
            left,
            op: BO::Add,
            right,
        } => {
            (is_alias_expr(left) && integer_literal_value(right).is_some())
                || (is_alias_expr(right) && integer_literal_value(left).is_some())
        }
        _ => false,
    }
}

fn parse_logical_or(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::logical_or => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_logical_and(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::or_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let right = parse_logical_and(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op: BinaryOp::LogicalOr,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_logical_and(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::logical_and => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_bitwise_or(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::and_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let right = parse_bitwise_or(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op: BinaryOp::LogicalAnd,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_bitwise_or(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::bitwise_or => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_bitwise_xor(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::bit_or_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let right = parse_bitwise_xor(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op: BinaryOp::BitOr,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_bitwise_xor(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::bitwise_xor => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_bitwise_and(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::bit_xor_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let right = parse_bitwise_and(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op: BinaryOp::BitXor,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_bitwise_and(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::bitwise_and => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_equality(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::bit_and_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let right = parse_equality(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op: BinaryOp::BitAnd,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_equality(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::equality => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_relational(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::eq_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let op = match chunk[0].as_str() {
                    "==" => BinaryOp::Equal,
                    "!=" => BinaryOp::NotEqual,
                    _ => return Err(ParseError::UnexpectedToken(chunk[0].as_rule())),
                };
                let right = parse_relational(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op,
                    right: Box::new(right),
                };
                // Type check literals only
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_relational(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::relational => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_shift(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                if chunk[0].as_rule() != Rule::rel_op {
                    return Err(ParseError::UnexpectedToken(chunk[0].as_rule()));
                }
                let op = match chunk[0].as_str() {
                    "<" => BinaryOp::LessThan,
                    "<=" => BinaryOp::LessEqual,
                    ">" => BinaryOp::GreaterThan,
                    ">=" => BinaryOp::GreaterEqual,
                    _ => return Err(ParseError::UnexpectedToken(chunk[0].as_rule())),
                };
                let right = parse_shift(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_shift(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::shift => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_additive(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                let op = match chunk[0].as_str() {
                    "<<" => BinaryOp::ShiftLeft,
                    ">>" => BinaryOp::ShiftRight,
                    _ => return Err(ParseError::UnexpectedToken(chunk[0].as_rule())),
                };
                let right = parse_additive(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_additive(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::additive => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_term(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }
                let op = match chunk[0].as_str() {
                    "+" => BinaryOp::Add,
                    "-" => BinaryOp::Subtract,
                    _ => return Err(ParseError::UnexpectedToken(chunk[0].as_rule())),
                };
                let right = parse_term(chunk[1].clone())?;
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op,
                    right: Box::new(right),
                };
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }
                left = expr;
            }
            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_condition(pair: Pair<Rule>) -> Result<Expr> {
    debug!(
        "parse_condition: {:?} = '{}'",
        pair.as_rule(),
        pair.as_str().trim()
    );
    match pair.as_rule() {
        Rule::condition => {
            // Condition now accepts a full expression (equality/relational/additive/etc.)
            let inner_expr_pair = pair
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            let expr = parse_expr(inner_expr_pair)?;
            // Basic type check of the resulting expression
            if let Err(err) = infer_type(&expr) {
                return Err(ParseError::TypeError(err));
            }
            Ok(expr)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_else_clause(pair: Pair<Rule>) -> Result<Statement> {
    let inner = pair
        .into_inner()
        .next()
        .ok_or(ParseError::InvalidExpression)?;
    match inner.as_rule() {
        Rule::if_stmt => {
            // Directly parse if statement for else if
            debug!("Parsing else if statement");
            let mut inner_pairs = inner.into_inner();
            let condition_pair = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
            debug!(
                "else if condition_pair: {:?} = '{}'",
                condition_pair.as_rule(),
                condition_pair.as_str().trim()
            );
            let condition = parse_condition(condition_pair)?;

            // Parse then body statements
            let mut then_body = Vec::new();
            let mut else_body = None;

            for pair in inner_pairs {
                match pair.as_rule() {
                    Rule::statement => {
                        then_body.push(parse_statement(pair)?);
                    }
                    Rule::else_clause => {
                        else_body = Some(Box::new(parse_else_clause(pair)?));
                        break;
                    }
                    _ => return Err(ParseError::UnexpectedToken(pair.as_rule())),
                }
            }

            Ok(Statement::If {
                condition,
                then_body,
                else_body,
            })
        }
        _ => {
            // Parse else block statements
            let mut else_body = Vec::new();
            for node in inner.into_inner() {
                match node.as_rule() {
                    Rule::statement => {
                        else_body.push(parse_statement(node)?);
                    }
                    // Some grammars flatten block children to concrete statements (e.g., print_stmt)
                    Rule::print_stmt => {
                        let content = node
                            .into_inner()
                            .next()
                            .ok_or(ParseError::InvalidExpression)?;
                        let pr = parse_print_content(content)?;
                        else_body.push(Statement::Print(pr));
                    }
                    _ => return Err(ParseError::UnexpectedToken(node.as_rule())),
                }
            }
            Ok(Statement::Block(else_body))
        }
    }
}

fn parse_term(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::term => {
            let mut pairs = pair.into_inner();
            let first = pairs.next().ok_or(ParseError::InvalidExpression)?;
            let mut left = parse_unary(first)?;

            for chunk in chunks_of_two(pairs) {
                if chunk.len() != 2 {
                    return Err(ParseError::InvalidExpression);
                }

                let op = match chunk[0].as_str() {
                    "*" => BinaryOp::Multiply,
                    "/" => BinaryOp::Divide,
                    "%" => BinaryOp::Modulo,
                    _ => return Err(ParseError::UnexpectedToken(chunk[0].as_rule())),
                };

                let right = parse_unary(chunk[1].clone())?;

                // Check type consistency for binary operations
                let expr = Expr::BinaryOp {
                    left: Box::new(left),
                    op,
                    right: Box::new(right),
                };

                // Only check type consistency for literals here
                if let Err(err) = infer_type(&expr) {
                    return Err(ParseError::TypeError(err));
                }

                left = expr;
            }

            Ok(left)
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_unary(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::unary => {
            let mut inner = pair.into_inner();
            let first = inner.next().ok_or(ParseError::InvalidExpression)?;
            match first.as_rule() {
                Rule::factor => parse_factor(first),
                // '-' ~ unary
                Rule::neg_unary => {
                    let u = first
                        .into_inner()
                        .next()
                        .ok_or(ParseError::InvalidExpression)?;
                    let right = parse_unary(u)?;
                    let expr = Expr::BinaryOp {
                        left: Box::new(Expr::Int(0)),
                        op: BinaryOp::Subtract,
                        right: Box::new(right),
                    };
                    if let Err(err) = infer_type(&expr) {
                        return Err(ParseError::TypeError(err));
                    }
                    Ok(expr)
                }
                // '!' ~ unary
                Rule::not_unary => {
                    let u = first
                        .into_inner()
                        .next()
                        .ok_or(ParseError::InvalidExpression)?;
                    let right = parse_unary(u)?;
                    Ok(Expr::UnaryNot(Box::new(right)))
                }
                Rule::bit_not_unary => {
                    let u = first
                        .into_inner()
                        .next()
                        .ok_or(ParseError::InvalidExpression)?;
                    let right = parse_unary(u)?;
                    let expr = Expr::UnaryBitNot(Box::new(right));
                    if let Err(err) = infer_type(&expr) {
                        return Err(ParseError::TypeError(err));
                    }
                    Ok(expr)
                }
                _ => Err(ParseError::UnexpectedToken(first.as_rule())),
            }
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_factor(pair: Pair<Rule>) -> Result<Expr> {
    match pair.as_rule() {
        Rule::factor => {
            let inner = pair
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            match inner.as_rule() {
                Rule::memcmp_call => parse_builtin_call(inner),
                Rule::strncmp_call => parse_builtin_call(inner),
                Rule::starts_with_call => parse_builtin_call(inner),
                Rule::hex_call => parse_builtin_call(inner),
                Rule::postfix_access => parse_postfix_access(inner),
                Rule::cast_call => parse_cast_call(inner),
                Rule::chain_access => parse_chain_access(inner),
                Rule::pointer_deref => parse_pointer_deref(inner),
                Rule::address_of => parse_address_of(inner),
                Rule::int => match inner.as_str().parse::<i64>() {
                    Ok(value) => Ok(Expr::Int(value)),
                    Err(_) => Err(ParseError::TypeError(
                        "invalid decimal integer literal".to_string(),
                    )),
                },
                Rule::hex_int => {
                    // strip 0x and parse as hex
                    let s = inner.as_str();
                    match i64::from_str_radix(&s[2..], 16) {
                        Ok(v) => Ok(Expr::Int(v)),
                        Err(_) => Err(ParseError::TypeError(
                            "invalid hex integer literal".to_string(),
                        )),
                    }
                }
                Rule::oct_int => {
                    let s = inner.as_str();
                    match i64::from_str_radix(&s[2..], 8) {
                        Ok(v) => Ok(Expr::Int(v)),
                        Err(_) => Err(ParseError::TypeError(
                            "invalid octal integer literal".to_string(),
                        )),
                    }
                }
                Rule::bin_int => {
                    let s = inner.as_str();
                    match i64::from_str_radix(&s[2..], 2) {
                        Ok(v) => Ok(Expr::Int(v)),
                        Err(_) => Err(ParseError::TypeError(
                            "invalid binary integer literal".to_string(),
                        )),
                    }
                }
                // Floats are not supported by scripts/runtime; reject early with friendly error
                Rule::float => Err(ParseError::TypeError(
                    "float literals are not supported".to_string(),
                )),
                Rule::string => {
                    // Remove quotes at the beginning and end
                    let raw_value = inner.as_str();
                    let value = &raw_value[1..raw_value.len() - 1];
                    Ok(Expr::String(value.to_string()))
                }
                Rule::bool => {
                    let val = inner.as_str() == "true";
                    Ok(Expr::Bool(val))
                }
                Rule::identifier => {
                    let name = inner.as_str().to_string();
                    Ok(Expr::Variable(name))
                }
                Rule::array_access => parse_array_access(inner),
                Rule::member_access => parse_member_access(inner),
                Rule::special_var => {
                    let var_name = inner.as_str().to_string();
                    Ok(Expr::SpecialVar(var_name))
                }
                Rule::expr => parse_expr(inner),
                _ => Err(ParseError::UnexpectedToken(inner.as_rule())),
            }
        }
        _ => Err(ParseError::UnexpectedToken(pair.as_rule())),
    }
}

fn parse_builtin_call(pair: Pair<Rule>) -> Result<Expr> {
    // pair is memcmp_call / strncmp_call / starts_with_call / hex_call
    let rule = pair.as_rule();
    let mut it = pair.into_inner();
    // First token inside is the function name as identifier within the rule text; easier approach: use rule to select
    match rule {
        Rule::memcmp_call => {
            // grammar: memcmp("(" expr "," expr ["," expr] ")")
            let mut nodes: Vec<_> = it.collect();
            if nodes.len() < 2 || nodes.len() > 3 {
                return Err(ParseError::InvalidExpression);
            }
            let a_expr = parse_expr(nodes.remove(0))?;
            let b_expr = parse_expr(nodes.remove(0))?;

            // Disallow obviously invalid types early
            if matches!(a_expr, Expr::Bool(_)) || matches!(b_expr, Expr::Bool(_)) {
                return Err(ParseError::TypeError(
                    "memcmp pointer arguments cannot be boolean; use an address or hex(...)"
                        .to_string(),
                ));
            }
            if matches!(a_expr, Expr::String(_)) || matches!(b_expr, Expr::String(_)) {
                return Err(ParseError::TypeError(
                    "memcmp does not accept string literals; use strncmp for strings".to_string(),
                ));
            }

            // Helper to get hex length (bytes)
            let hex_len = |e: &Expr| -> Option<usize> {
                if let Expr::BuiltinCall { name, args } = e {
                    if name == "hex" {
                        if let Some(Expr::String(s)) = args.first() {
                            return Some(s.len() / 2);
                        }
                    }
                }
                None
            };

            let n_expr = if let Some(n_node) = nodes.first() {
                // With explicit len: reuse previous literal checks
                let n_expr = parse_expr(n_node.clone())?;
                if matches!(n_expr, Expr::Bool(_)) {
                    return Err(ParseError::TypeError(
                        "memcmp length must be an integer or expression, not boolean".to_string(),
                    ));
                }
                let literal_len_opt: Option<isize> = match &n_expr {
                    Expr::Int(n) => Some(*n as isize),
                    Expr::BinaryOp {
                        left,
                        op: BinaryOp::Subtract,
                        right,
                    } => {
                        if matches!(left.as_ref(), Expr::Int(0)) {
                            if let Expr::Int(k) = right.as_ref() {
                                Some(-(*k as isize))
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    }
                    _ => None,
                };
                if let Some(n) = literal_len_opt {
                    if n < 0 {
                        return Err(ParseError::TypeError(
                            "memcmp length must be non-negative".to_string(),
                        ));
                    }
                    let l = n as usize;
                    if let Some(la) = hex_len(&a_expr) {
                        if l > la {
                            return Err(ParseError::TypeError(format!(
                                "memcmp length ({l}) exceeds hex pattern size on left side ({la} bytes)"
                            )));
                        }
                    }
                    if let Some(lb) = hex_len(&b_expr) {
                        if l > lb {
                            return Err(ParseError::TypeError(format!(
                                "memcmp length ({l}) exceeds hex pattern size on right side ({lb} bytes)"
                            )));
                        }
                    }
                }
                n_expr
            } else {
                // No len provided: allow only when at least one side is hex(...)
                let la = hex_len(&a_expr);
                let lb = hex_len(&b_expr);
                match (la, lb) {
                    (Some(l), None) | (None, Some(l)) => Expr::Int(l as i64),
                    (Some(la), Some(lb)) => {
                        if la != lb {
                            return Err(ParseError::TypeError(
                                "memcmp hex operands have different sizes; provide explicit len"
                                    .to_string(),
                            ));
                        }
                        Expr::Int(la as i64)
                    }
                    _ => {
                        return Err(ParseError::TypeError(
                            "memcmp without len requires at least one hex(...) operand".to_string(),
                        ))
                    }
                }
            };

            // Constant folding: memcmp(hex(...), hex(...), N)
            let as_hex = |e: &Expr| -> Option<String> {
                if let Expr::BuiltinCall { name, args } = e {
                    if name == "hex" {
                        if let Some(Expr::String(s)) = args.first() {
                            return Some(s.clone());
                        }
                    }
                }
                None
            };

            if let (Some(h1), Some(h2), Expr::Int(n)) = (as_hex(&a_expr), as_hex(&b_expr), &n_expr)
            {
                // Safe hex -> bytes (sanitized earlier to hex digits only)
                fn hex_to_bytes(s: &str) -> std::result::Result<Vec<u8>, ParseError> {
                    let mut out = Vec::with_capacity(s.len() / 2);
                    let bytes = s.as_bytes();
                    let mut i = 0;
                    while i + 1 < bytes.len() {
                        let h = bytes[i] as char;
                        let l = bytes[i + 1] as char;
                        let hv = h
                            .to_digit(16)
                            .ok_or_else(|| ParseError::TypeError("invalid hex digit".to_string()))?
                            as u8;
                        let lv = l
                            .to_digit(16)
                            .ok_or_else(|| ParseError::TypeError("invalid hex digit".to_string()))?
                            as u8;
                        out.push((hv << 4) | lv);
                        i += 2;
                    }
                    Ok(out)
                }

                let v1 = hex_to_bytes(&h1)?;
                let v2 = hex_to_bytes(&h2)?;
                let ln = (*n).max(0) as usize;
                let eq = v1.iter().take(ln).eq(v2.iter().take(ln));
                return Ok(Expr::Bool(eq));
            }

            Ok(Expr::BuiltinCall {
                name: "memcmp".to_string(),
                args: vec![a_expr, b_expr, n_expr],
            })
        }
        Rule::strncmp_call => {
            // grammar: strncmp("(" expr "," expr "," expr ")")
            let arg0 = parse_expr(it.next().ok_or(ParseError::InvalidExpression)?)?;
            let arg1 = parse_expr(it.next().ok_or(ParseError::InvalidExpression)?)?;
            let n_expr_parsed = parse_expr(it.next().ok_or(ParseError::InvalidExpression)?)?;
            let literal_len_opt: Option<isize> = match &n_expr_parsed {
                Expr::Int(n) => Some(*n as isize),
                Expr::BinaryOp {
                    left,
                    op: BinaryOp::Subtract,
                    right,
                } => {
                    if matches!(left.as_ref(), Expr::Int(0)) {
                        if let Expr::Int(k) = right.as_ref() {
                            Some(-(*k as isize))
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
                _ => None,
            };
            if literal_len_opt.is_some_and(|n| n < 0) {
                return Err(ParseError::TypeError(
                    "strncmp third argument must be non-negative".to_string(),
                ));
            }
            // Optional constant fold when both sides are string literals
            if let (Expr::String(a), Expr::String(b), Expr::Int(n_val)) =
                (&arg0, &arg1, &n_expr_parsed)
            {
                let ln = (*n_val).max(0) as usize;
                let eq = a
                    .as_bytes()
                    .iter()
                    .take(ln)
                    .eq(b.as_bytes().iter().take(ln));
                return Ok(Expr::Bool(eq));
            }
            Ok(Expr::BuiltinCall {
                name: "strncmp".to_string(),
                args: vec![arg0, arg1, n_expr_parsed],
            })
        }
        Rule::starts_with_call => {
            // grammar: starts_with("(" expr "," expr ")")
            let arg0 = parse_expr(it.next().ok_or(ParseError::InvalidExpression)?)?;
            let arg1 = parse_expr(it.next().ok_or(ParseError::InvalidExpression)?)?;
            // Constant fold when both are string literals
            if let (Expr::String(a), Expr::String(b)) = (&arg0, &arg1) {
                return Ok(Expr::Bool(a.as_bytes().starts_with(b.as_bytes())));
            }
            Ok(Expr::BuiltinCall {
                name: "starts_with".to_string(),
                args: vec![arg0, arg1],
            })
        }
        Rule::hex_call => {
            // grammar: hex("HEX...")
            // Validate at parse time: allow only hex digits with optional whitespace separators.
            let lit_node = it.next().ok_or(ParseError::InvalidExpression)?;
            if lit_node.as_rule() != Rule::string {
                return Err(ParseError::TypeError(
                    "hex expects a string literal".to_string(),
                ));
            }
            let raw = lit_node.as_str();
            let inner = &raw[1..raw.len() - 1];
            let mut sanitized = String::with_capacity(inner.len());
            for ch in inner.chars() {
                if ch.is_ascii_hexdigit() {
                    sanitized.push(ch);
                } else if ch == ' ' {
                    // allow spaces as separators (tabs not allowed)
                    continue;
                } else {
                    return Err(ParseError::TypeError(format!(
                        "hex literal contains non-hex character: '{ch}'"
                    )));
                }
            }
            if sanitized.len() % 2 == 1 {
                return Err(ParseError::TypeError(
                    "hex literal must contain an even number of hex digits".to_string(),
                ));
            }
            Ok(Expr::BuiltinCall {
                name: "hex".to_string(),
                // Store sanitized hex-only string; codegen will convert to bytes
                args: vec![Expr::String(sanitized)],
            })
        }
        _ => Err(ParseError::UnexpectedToken(rule)),
    }
}

fn parse_cast_call(pair: Pair<Rule>) -> Result<Expr> {
    let mut inner = pair.into_inner();
    let expr_pair = inner.next().ok_or(ParseError::InvalidExpression)?;
    let type_pair = inner.next().ok_or(ParseError::InvalidExpression)?;
    let raw_type = type_pair.as_str();
    let target_type = raw_type
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .ok_or_else(|| ParseError::SyntaxError("cast target type must be a string".to_string()))?
        .to_string();

    Ok(Expr::Cast {
        expr: Box::new(parse_expr(expr_pair)?),
        target_type,
    })
}

fn parse_postfix_access(pair: Pair<Rule>) -> Result<Expr> {
    let mut inner = pair.into_inner();
    let base = inner.next().ok_or(ParseError::InvalidExpression)?;
    let mut expr = match base.as_rule() {
        Rule::postfix_base => {
            let base_inner = base
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?;
            match base_inner.as_rule() {
                Rule::cast_call => parse_cast_call(base_inner)?,
                Rule::special_var => Expr::SpecialVar(base_inner.as_str().to_string()),
                Rule::identifier => Expr::Variable(base_inner.as_str().to_string()),
                Rule::expr => parse_expr(base_inner)?,
                _ => return Err(ParseError::UnexpectedToken(base_inner.as_rule())),
            }
        }
        _ => return Err(ParseError::UnexpectedToken(base.as_rule())),
    };

    for suffix in inner {
        let suffix_inner = suffix
            .into_inner()
            .next()
            .ok_or(ParseError::InvalidExpression)?;
        match suffix_inner.as_rule() {
            Rule::member_suffix => {
                let field = suffix_inner
                    .into_inner()
                    .next()
                    .ok_or(ParseError::InvalidExpression)?
                    .as_str()
                    .to_string();
                expr = Expr::MemberAccess(Box::new(expr), field);
            }
            Rule::index_suffix => {
                let index_pair = suffix_inner
                    .into_inner()
                    .next()
                    .ok_or(ParseError::InvalidExpression)?;
                let parsed_index = parse_expr(index_pair)?;
                let parsed_index = integer_literal_value(&parsed_index)
                    .map(Expr::Int)
                    .unwrap_or(parsed_index);
                expr = Expr::ArrayAccess(Box::new(expr), Box::new(parsed_index));
            }
            _ => return Err(ParseError::UnexpectedToken(suffix_inner.as_rule())),
        }
    }

    Ok(expr)
}

fn parse_trace_pattern(pair: Pair<Rule>) -> Result<TracePattern> {
    let inner = pair
        .into_inner()
        .next()
        .ok_or(ParseError::InvalidExpression)?;

    match inner.as_rule() {
        Rule::module_hex_address => {
            let mut parts = inner.into_inner();
            let module = parts
                .next()
                .ok_or(ParseError::InvalidExpression)?
                .as_str()
                .to_string();
            let hex = parts.next().ok_or(ParseError::InvalidExpression)?.as_str();
            let addr = match u64::from_str_radix(&hex[2..], 16) {
                Ok(v) => v,
                Err(_) => {
                    return Err(ParseError::SyntaxError(format!(
                        "module-qualified address '{hex}' is invalid or too large for u64"
                    )))
                }
            };
            Ok(TracePattern::AddressInModule {
                module,
                address: addr,
            })
        }
        Rule::hex_address => {
            let addr_str = inner.as_str();
            // Remove "0x" prefix and parse as hex
            let addr_hex = &addr_str[2..];
            let addr = match u64::from_str_radix(addr_hex, 16) {
                Ok(v) => v,
                Err(_) => {
                    return Err(ParseError::SyntaxError(format!(
                        "address '{addr_str}' is invalid or too large for u64"
                    )))
                }
            };
            Ok(TracePattern::Address(addr))
        }
        Rule::wildcard_pattern => {
            let pattern = inner.as_str().to_string();
            Ok(TracePattern::Wildcard(pattern))
        }
        Rule::function_name => {
            let func_name = inner
                .into_inner()
                .next()
                .ok_or(ParseError::InvalidExpression)?
                .as_str()
                .to_string();
            Ok(TracePattern::FunctionName(func_name))
        }
        Rule::source_line => {
            let mut parts = inner.into_inner();
            let file_path = parts
                .next()
                .ok_or(ParseError::InvalidExpression)?
                .as_str()
                .to_string();
            let line_pair = parts.next().ok_or(ParseError::InvalidExpression)?;
            let line_number = line_pair
                .as_str()
                .parse::<u32>()
                .map_err(|_| ParseError::InvalidExpression)?;
            Ok(TracePattern::SourceLine {
                file_path,
                line_number,
            })
        }
        _ => Err(ParseError::UnexpectedToken(inner.as_rule())),
    }
}

fn parse_print_content(pair: Pair<Rule>) -> Result<PrintStatement> {
    info!(
        "parse_print_content: rule={:?} text=\"{}\"",
        pair.as_rule(),
        pair.as_str().trim()
    );
    // Flatten any nested print_content nodes into a single list of children
    fn collect_flattened<'a>(p: Pair<'a, Rule>, out: &mut Vec<Pair<'a, Rule>>) {
        if p.as_rule() == Rule::print_content {
            for c in p.into_inner() {
                collect_flattened(c, out);
            }
        } else {
            out.push(p);
        }
    }

    let mut flat: Vec<Pair<Rule>> = Vec::new();
    collect_flattened(pair, &mut flat);
    info!(
        "parse_print_content: flat_rules=[{}]",
        flat.iter()
            .map(|p| format!("{:?}", p.as_rule()))
            .collect::<Vec<_>>()
            .join(", ")
    );
    if flat.is_empty() {
        return Err(ParseError::InvalidExpression);
    }

    // Prefer an explicit format_expr if present
    if let Some(fmt_idx) = flat.iter().position(|p| p.as_rule() == Rule::format_expr) {
        let fmt_pair = flat.remove(fmt_idx);
        info!("parse_print_content: branch=format_expr");
        let mut inner_pairs = fmt_pair.into_inner();
        let format_string = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
        let format_content = &format_string.as_str()[1..format_string.as_str().len() - 1];
        let mut args = Vec::new();
        for arg_pair in inner_pairs {
            args.push(parse_expr(arg_pair)?);
        }
        info!(
            "parse_print_content: fmt='{}' argc={}",
            format_content,
            args.len()
        );
        FormatValidator::validate_format_arguments(format_content, &args)?;
        return Ok(PrintStatement::Formatted {
            format: format_content.to_string(),
            args,
        });
    }

    // Else, if first is a string and followed by one or more exprs, treat as flattened format
    if flat[0].as_rule() == Rule::string && flat.len() >= 2 {
        info!("parse_print_content: branch=flattened_string_with_args");
        let content_quoted = flat[0].as_str();
        let content = &content_quoted[1..content_quoted.len() - 1];
        let mut args = Vec::new();
        for p in flat.iter().skip(1) {
            if p.as_rule() != Rule::expr {
                return Err(ParseError::UnexpectedToken(p.as_rule()));
            }
            args.push(parse_expr(p.clone())?);
        }
        info!("parse_print_content: fmt='{}' argc={}", content, args.len());
        FormatValidator::validate_format_arguments(content, &args)?;
        return Ok(PrintStatement::Formatted {
            format: content.to_string(),
            args,
        });
    }

    // Single string or single expr
    match flat[0].as_rule() {
        Rule::string => {
            info!("parse_print_content: branch=plain_string");
            let content = flat[0].as_str();
            let content = &content[1..content.len() - 1];
            Ok(PrintStatement::String(content.to_string()))
        }
        Rule::expr => {
            info!("parse_print_content: branch=complex_variable");
            let expr = parse_expr(flat[0].clone())?;
            Ok(PrintStatement::ComplexVariable(expr))
        }
        other => {
            info!("parse_print_content: branch=unexpected rule={:?}", other);
            Err(ParseError::UnexpectedToken(other))
        }
    }
}

// Parse complex variable expressions (person.name, arr[0], etc.)
fn parse_complex_variable(pair: Pair<Rule>) -> Result<Expr> {
    debug!(
        "parse_complex_variable: {:?} = \"{}\"",
        pair.as_rule(),
        pair.as_str().trim()
    );

    let inner = pair
        .into_inner()
        .next()
        .ok_or(ParseError::InvalidExpression)?;
    match inner.as_rule() {
        Rule::chain_access => parse_chain_access(inner),
        Rule::array_access => parse_array_access(inner),
        Rule::member_access => parse_member_access(inner),
        Rule::pointer_deref => parse_pointer_deref(inner),
        Rule::address_of => parse_address_of(inner),
        _ => Err(ParseError::UnexpectedToken(inner.as_rule())),
    }
}

// Parse chain access: person.name.first
fn parse_chain_access(pair: Pair<Rule>) -> Result<Expr> {
    let mut chain: Vec<String> = Vec::new();
    let mut opt_index: Option<Expr> = None;
    for inner_pair in pair.into_inner() {
        match inner_pair.as_rule() {
            Rule::identifier => {
                chain.push(inner_pair.as_str().to_string());
            }
            Rule::expr => {
                // Array tail index can be a literal or a runtime expression.
                let parsed = parse_expr(inner_pair)?;
                opt_index = Some(
                    integer_literal_value(&parsed)
                        .map(Expr::Int)
                        .unwrap_or(parsed),
                );
            }
            _ => {}
        }
    }

    if chain.is_empty() {
        return Err(ParseError::InvalidExpression);
    }

    // Build base expression from the chain identifiers
    let mut expr = Expr::Variable(chain[0].clone());
    for seg in &chain[1..] {
        expr = Expr::MemberAccess(Box::new(expr), seg.clone());
    }

    // If there's a trailing index, convert to ArrayAccess on the built base
    if let Some(idx) = opt_index {
        expr = Expr::ArrayAccess(Box::new(expr), Box::new(idx));
    }

    Ok(expr)
}

// Parse array access: arr[index]
fn parse_array_access(pair: Pair<Rule>) -> Result<Expr> {
    let mut inner_pairs = pair.into_inner();
    let array_name = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;
    let index_expr = inner_pairs.next().ok_or(ParseError::InvalidExpression)?;

    let _array_expr = Box::new(Expr::Variable(array_name.as_str().to_string()));
    let parsed_index = parse_expr(index_expr)?;
    let parsed_index = integer_literal_value(&parsed_index)
        .map(Expr::Int)
        .unwrap_or(parsed_index);

    // Build base array access expression
    let mut expr = Expr::ArrayAccess(
        Box::new(Expr::Variable(array_name.as_str().to_string())),
        Box::new(parsed_index),
    );

    // Consume trailing .field segments if present
    for next in inner_pairs {
        // Any remaining tokens are member identifiers
        let m = next.as_str().to_string();
        expr = Expr::MemberAccess(Box::new(expr), m);
    }

    Ok(expr)
}

// Parse member access: person.name
fn parse_member_access(pair: Pair<Rule>) -> Result<Expr> {
    let mut parts = pair.into_inner();
    let base = parts
        .next()
        .ok_or(ParseError::InvalidExpression)?
        .as_str()
        .to_string();

    // Collect all subsequent identifiers after the base
    let mut tail: Vec<String> = Vec::new();
    for p in parts {
        tail.push(p.as_str().to_string());
    }

    // If there is only one member, keep MemberAccess for simplicity.
    // For multi-level chains like a.b.c, normalize to ChainAccess([a, b, c])
    match tail.len() {
        0 => Err(ParseError::InvalidExpression),
        1 => Ok(Expr::MemberAccess(
            Box::new(Expr::Variable(base)),
            tail.remove(0),
        )),
        _ => {
            let mut chain = Vec::with_capacity(1 + tail.len());
            chain.push(base);
            chain.extend(tail);
            Ok(Expr::ChainAccess(chain))
        }
    }
}

// Parse pointer dereference: *ptr
fn parse_pointer_deref(pair: Pair<Rule>) -> Result<Expr> {
    let mut inner = pair.into_inner();
    let target = inner.next().ok_or(ParseError::InvalidExpression)?;
    let parsed = match target.as_rule() {
        Rule::expr => parse_expr(target)?,
        Rule::postfix_access => parse_postfix_access(target)?,
        Rule::cast_call => parse_cast_call(target)?,
        Rule::complex_variable => parse_complex_variable(target)?,
        Rule::special_var => Expr::SpecialVar(target.as_str().to_string()),
        Rule::identifier => Expr::Variable(target.as_str().to_string()),
        _ => return Err(ParseError::UnexpectedToken(target.as_rule())),
    };
    // Early normalization: *(&x) => x
    match parsed {
        Expr::AddressOf(inner_expr) => Ok(*inner_expr),
        other => Ok(Expr::PointerDeref(Box::new(other))),
    }
}

// Parse address-of: &expr
fn parse_address_of(pair: Pair<Rule>) -> Result<Expr> {
    let mut inner = pair.into_inner();
    let target = inner.next().ok_or(ParseError::InvalidExpression)?;
    let parsed = match target.as_rule() {
        Rule::expr => parse_expr(target)?,
        Rule::postfix_access => parse_postfix_access(target)?,
        Rule::cast_call => parse_cast_call(target)?,
        Rule::complex_variable => parse_complex_variable(target)?,
        Rule::special_var => Expr::SpecialVar(target.as_str().to_string()),
        Rule::identifier => Expr::Variable(target.as_str().to_string()),
        _ => return Err(ParseError::UnexpectedToken(target.as_rule())),
    };
    // Early normalization: &(*p) => p
    match parsed {
        Expr::PointerDeref(inner_expr) => Ok(*inner_expr),
        other => Ok(Expr::AddressOf(Box::new(other))),
    }
}

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

    #[test]
    fn parse_memcmp_builtin_in_if_should_succeed() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], &buf[1], 16) { print "EQ"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_cast_member_and_index_access() {
        let script = r#"
trace foo {
    print cast($arg0, "struct request *").id;
    print cast($arg1, "u32 *")[2];
    print *cast($arg1, "u32 *");
    print &cast($arg0, "struct request *").id;
}
"#;
        let program = parse(script).expect("parse should succeed");
        let Statement::TracePoint { body, .. } = &program.statements[0] else {
            panic!("expected trace point");
        };
        assert!(matches!(
            &body[0],
            Statement::Print(PrintStatement::ComplexVariable(Expr::MemberAccess(obj, field)))
                if field == "id" && matches!(obj.as_ref(), Expr::Cast { .. })
        ));
        assert!(matches!(
            &body[1],
            Statement::Print(PrintStatement::ComplexVariable(Expr::ArrayAccess(base, index)))
                if matches!(base.as_ref(), Expr::Cast { .. })
                    && matches!(index.as_ref(), Expr::Int(2))
        ));
        assert!(matches!(
            &body[2],
            Statement::Print(PrintStatement::ComplexVariable(Expr::PointerDeref(inner)))
                if matches!(inner.as_ref(), Expr::Cast { .. })
        ));
        assert!(matches!(
            &body[3],
            Statement::Print(PrintStatement::ComplexVariable(Expr::AddressOf(inner)))
                if matches!(
                    inner.as_ref(),
                    Expr::MemberAccess(obj, field)
                        if field == "id" && matches!(obj.as_ref(), Expr::Cast { .. })
                )
        ));
    }

    #[test]
    fn parse_memcmp_with_dynamic_len() {
        let script = r#"
trace foo {
    let n = 10;
    if memcmp(&buf[0], &buf[0], n) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_if_else_with_flattened_format_and_star_len() {
        // else branch contains a flattened format print with {:s.*} and two args
        let script = r#"
trace src/http/ngx_http_request.c:1845 {
    if strncmp(host.data, "ghostscope", 10) {
        print "We got the request {}", *r;
    } else {
        print "The other hostname is {:s.*}", host.len, host.data;
    }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_len_zero_and_negative() {
        let script = r#"
trace foo {
    if memcmp(&p[0], &q[0], 0) { print "Z0"; }
    let k = -5;
    if memcmp(&p[0], &q[0], k) { print "NEG"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_numeric_literals_hex_oct_bin_and_memcmp_usage() {
        let script = r#"
trace foo {
    let a = 0x10;   // 16
    let b = 0o755;  // 493
    let c = 0b1010; // 10
    // use in memcmp length
    if memcmp(&buf[0], &buf[0], 0x20) { print "H"; }
    if memcmp(&buf[0], &buf[0], 0o40) { print "O"; }
    if memcmp(&buf[0], &buf[0], 0b100000) { print "B"; }
    // use numeric literal as pointer address for second arg
    if memcmp(&buf[0], 0x7fff0000, 16) { print "P"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_hex_builtin() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("504F"), 2) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_with_numeric_pointers_and_len_bases() {
        let script = r#"
trace foo {
    let n = 0x10;
    if memcmp(0x1000, 0x2000, n) { print "NP"; }
    if memcmp(0o4000, 0b1000000000000, 0o20) { print "NP2"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_hex_with_non_hex_char_should_fail() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("G0"), 1) { print "X"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for non-hex char"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("hex literal contains non-hex character"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_hex_with_odd_digits_should_fail() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("123"), 1) { print "X"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for odd-length hex"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("even number of hex digits"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_hex_with_spaces_should_succeed() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("4c 49 42 5f"), 4) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_alias_declaration_address_of_and_member_access() {
        let script = r#"
trace foo {
    let p = &buf[0];
    let s = obj.field;
}
"#;
        let prog = parse(script).expect("parse ok");
        let stmt0 = prog.statements.first().expect("trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => {
                // Only the address-of form should be alias; member access is a value binding
                assert!(matches!(body[0], Statement::AliasDeclaration { .. }));
                assert!(matches!(body[1], Statement::VarDeclaration { .. }));
            }
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_alias_declaration_with_constant_offset() {
        let script = r#"
trace foo {
    let p = &arr[0] + 16;
    let q = 32 + &arr[0];
}
"#;
        let prog = parse(script).expect("parse ok");
        let stmt0 = prog.statements.first().expect("trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => {
                assert!(matches!(body[0], Statement::AliasDeclaration { .. }));
                assert!(matches!(body[1], Statement::AliasDeclaration { .. }));
            }
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_member_access_scalar_not_alias() {
        let script = r#"
trace foo {
    let level = record.level;
}
"#;
        let prog = parse(script).expect("parse ok");
        let stmt0 = prog.statements.first().expect("trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => {
                assert!(matches!(body[0], Statement::VarDeclaration { .. }));
            }
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_memcmp_rejects_string_literal() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], "PO", 2) { print "X"; }
}
"#;
        let r = parse(script);
        assert!(
            matches!(r, Err(ParseError::TypeError(ref msg)) if msg.contains("memcmp does not accept string literals")),
            "expected type error, got: {r:?}"
        );
    }

    #[test]
    fn parse_memcmp_rejects_bool_args_and_len() {
        // Bool as pointer argument
        let s1 = r#"
trace foo { if memcmp(true, hex("00"), 1) { print "X"; } }
"#;
        let r1 = parse(s1);
        assert!(r1.is_err());

        // Bool as length
        let s2 = r#"
trace foo { if memcmp(&p[0], hex("00"), false) { print "X"; } }
"#;
        let r2 = parse(s2);
        assert!(
            matches!(r2, Err(ParseError::TypeError(ref msg)) if msg.contains("length must be")),
            "unexpected: {r2:?}"
        );
    }

    #[test]
    fn parse_strncmp_constant_folds_on_two_literals() {
        // equal for first 2 bytes
        let s = r#"
trace foo {
    if strncmp("abc", "abd", 2) { print "T"; } else { print "F"; }
}
"#;
        let prog = parse(s).expect("parse ok");
        // Walk down to the If condition and ensure it became a Bool(true)
        let stmt0 = prog.statements.first().expect("one trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => {
                    assert!(matches!(condition, Expr::Bool(true)));
                }
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_strncmp_requires_one_string_side_error() {
        let s = r#"
trace foo {
    if strncmp(1, 2, 1) { print "X"; }
}
"#;
        let r = parse(s);
        // Parser now accepts generic expr, so error will occur in compiler stage; ensure parse ok here
        assert!(
            r.is_ok(),
            "parse should succeed; semantic error in compiler"
        );
    }

    #[test]
    fn parse_memcmp_constant_folds_on_two_hex() {
        let s = r#"
trace foo {
    if memcmp(hex("504f"), hex("504F"), 2) { print "EQ"; } else { print "NE"; }
}
"#;
        let prog = parse(s).expect("parse ok");
        let stmt0 = prog.statements.first().expect("one trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => assert!(matches!(condition, Expr::Bool(true))),
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }

        // Mismatch without explicit len but equal sizes
        let s2 = r#"
trace foo {
    if memcmp(hex("504f"), hex("514f")) { print "EQ"; } else { print "NE"; }
}
"#;
        let prog2 = parse(s2).expect("parse ok");
        let stmt02 = prog2.statements.first().expect("one trace");
        match stmt02 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => assert!(matches!(condition, Expr::Bool(false))),
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_starts_with_constant_folds_on_two_literals() {
        let s = r#"
trace foo {
    if starts_with("abcdef", "abc") { print "T"; } else { print "F"; }
}
"#;
        let prog = parse(s).expect("parse ok");
        let stmt0 = prog.statements.first().expect("one trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => assert!(matches!(condition, Expr::Bool(true))),
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }

        let s2 = r#"
trace foo {
    if starts_with("ab", "abc") { print "T"; } else { print "F"; }
}
"#;
        let prog2 = parse(s2).expect("parse ok");
        let stmt02 = prog2.statements.first().expect("one trace");
        match stmt02 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => assert!(matches!(condition, Expr::Bool(false))),
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_memcmp_hex_len_exceeds_left_should_fail() {
        // hex has 2 bytes, len=3 should error on left side
        let script = r#"
trace foo {
    if memcmp(hex("504f"), &buf[0], 3) { print "X"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for len > hex(left) size"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("exceeds hex pattern size on left side"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_memcmp_hex_len_exceeds_right_should_fail() {
        // hex has 2 bytes, len=5 should error on right side
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("50 4f"), 5) { print "X"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for len > hex(right) size"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("exceeds hex pattern size on right side"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_memcmp_hex_negative_len_should_fail() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("50 4f"), -1) { print "X"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for negative len"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("length must be non-negative"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_memcmp_hex_len_equal_should_succeed() {
        // hex has 4 bytes, len=4 OK
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("de ad be ef"), 4) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_hex_infers_len_left_should_succeed() {
        let script = r#"
trace foo {
    if memcmp(hex("50 4f"), &buf[0]) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_hex_infers_len_right_should_succeed() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], hex("de ad be ef")) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_assignment_is_rejected_with_friendly_message() {
        let script = r#"
trace foo {
    let a = 1;
    a = 2;
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected assignment error for immutable variables"),
            Err(ParseError::TypeError(msg)) => {
                assert!(
                    msg.contains("Assignment is not supported"),
                    "unexpected msg: {msg}"
                );
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_starts_with_accepts_two_exprs() {
        // Both sides are expr (identifiers); grammar should accept
        let script = r#"
trace foo {
    if starts_with(name, s) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_strncmp_accepts_two_exprs_and_len() {
        let script = r#"
trace foo {
    if strncmp(lhs, rhs, 3) { print "EQ"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_strncmp_negative_len_rejected() {
        // Negative literal lengths are rejected early.
        let script = r#"
trace foo {
    if strncmp(lhs, rhs, -1) { print "X"; }
}
"#;
        let r = parse(script);
        assert!(r.is_err(), "expected parse error for negative length");
        if let Err(ParseError::TypeError(msg)) = r {
            assert!(msg.contains("non-negative"), "unexpected msg: {msg}");
        }
    }

    #[test]
    fn parse_strncmp_accepts_nonliteral_len() {
        let script = r#"
trace foo {
    let n = 3;
    if strncmp(lhs, rhs, n) { print "X"; }
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_memcmp_missing_len_without_hex_should_fail() {
        let script = r#"
trace foo {
    if memcmp(&buf[0], &buf[1]) { print "OK"; }
}
"#;
        let r = parse(script);
        assert!(
            r.is_err(),
            "expected parse error for missing len without hex"
        );
    }

    #[test]
    fn parse_memcmp_both_hex_mismatch_should_fail() {
        let script = r#"
trace foo {
    if memcmp(hex("50"), hex("504f")) { print "OK"; }
}
"#;
        let r = parse(script);
        match r {
            Ok(_) => panic!("expected parse error for mismatched hex sizes"),
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("different sizes"), "unexpected msg: {msg}");
            }
            Err(e) => panic!("unexpected error variant: {e:?}"),
        }
    }

    #[test]
    fn parse_format_static_len_bases_in_prints() {
        // Validate that static length .N supports 0x/0o/0b in formatted prints
        let script = r#"
trace foo {
    print "HX={:x.0x10}", buf;
    print "HS={:s.0o20}", buf;
    print "HB={:X.0b1000}", buf;
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_trace_patterns_function_line_address_wildcard() {
        // Function name
        let s1 = r#"trace main { print "OK"; }"#;
        assert!(parse(s1).is_ok());

        // Source line with path and hyphen
        let s2 = r#"trace /tmp/test-file.c:42 { print "L"; }"#;
        assert!(parse(s2).is_ok());

        // Hex address
        let s3 = r#"trace 0x401234 { print "A"; }"#;
        assert!(parse(s3).is_ok());

        // Wildcard
        let s4 = r#"trace printf* { print "W"; }"#;
        assert!(parse(s4).is_ok());

        // Module-qualified address
        let s5 = r#"trace /lib/x86_64-linux-gnu/libc.so.6:0x1234 { print "M"; }"#;
        assert!(parse(s5).is_ok());
    }

    #[test]
    fn parse_identifiers_can_start_with_underscore() {
        let function = r#"trace __UpdateTicketInformation { print "OK"; }"#;
        assert!(parse(function).is_ok());

        let wildcard = r#"trace __builtin_* { print "W"; }"#;
        assert!(parse(wildcard).is_ok());

        let script = r#"
trace _start {
    let _ticket = __dwarf_value;
    print _ticket;
}
"#;
        assert!(parse(script).is_ok());
    }

    #[test]
    fn parse_module_hex_address_overflow_should_error() {
        // Address exceeds u64 (17 hex digits) -> parse error, not 0 fallback
        let s = r#"trace libfoo.so:0x10000000000000000 { print "X"; }"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => assert!(msg.contains("too large for u64")),
            other => panic!("expected friendly SyntaxError, got {other:?}"),
        }
    }

    #[test]
    fn parse_hex_address_overflow_should_error() {
        let s = r#"trace 0x10000000000000000 { print "X"; }"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => assert!(msg.contains("too large for u64")),
            other => panic!("expected friendly SyntaxError, got {other:?}"),
        }
    }

    #[test]
    fn parse_special_variables_basic() {
        // $pid/$tid/$host_pid/$input_pid/$timestamp in expressions and prints
        let script = r#"
trace foo {
    if $pid == 123 && $tid != 0 && $host_pid != 0 && $input_pid == 123 { print "PID_TID"; }
    print $timestamp;
    print "P:{} T:{} HP:{} IN:{} TS:{}", $pid, $tid, $host_pid, $input_pid, $timestamp;
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_chain_and_array_access() {
        // Member/chain and array tail index
        let script = r#"
trace foo {
    print person.name.first;
    print arr[0];
    // Supported: top-level array access with trailing member
    print ifaces[0].mtu;
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_pointer_and_address_of() {
        let script = r#"
trace foo {
    print *ptr;
    print &var;
    print *(arr_ptr);
}
"#;
        let r = parse(script);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_nested_trace_is_rejected() {
        let s = r#"
trace foo {
    trace bar { print "X"; }
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => assert!(msg.contains("cannot be nested")),
            other => panic!("expected SyntaxError for nested trace, got {other:?}"),
        }
    }

    #[test]
    fn parse_float_literal_is_rejected() {
        let s = r#"
trace foo {
    let x = 1.23;
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("float literals are not supported"))
            }
            other => panic!("expected TypeError for float literal, got {other:?}"),
        }
    }

    #[test]
    fn parse_unclosed_print_string_reports_friendly_error() {
        let bad = r#"
trace foo {
    print "Unclosed {}, value
}
"#;
        let r = parse(bad);
        match r {
            Err(ParseError::SyntaxError(msg)) => assert!(msg.contains("Unclosed string literal")),
            other => panic!("expected SyntaxError, got {other:?}"),
        }
    }

    #[test]
    fn parse_array_index_accepts_dynamic_expr() {
        // Dynamic index on top-level array
        let s1 = r#"
trace foo {
    print arr[i];
}
"#;
        let r1 = parse(s1).expect("dynamic top-level index should parse");
        match r1.statements.first().expect("trace") {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::Print(PrintStatement::ComplexVariable(Expr::ArrayAccess(_, index))) => {
                    assert!(matches!(index.as_ref(), Expr::Variable(name) if name == "i"))
                }
                other => panic!("unexpected first print body: {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }

        // Dynamic index at chain tail
        let s2 = r#"
trace foo {
    print obj.arr[i - (i / 0x8) * 0x8];
}
"#;
        let r2 = parse(s2).expect("dynamic chain index should parse");
        match r2.statements.first().expect("trace") {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::Print(PrintStatement::ComplexVariable(Expr::ArrayAccess(_, index))) => {
                    assert!(matches!(index.as_ref(), Expr::BinaryOp { .. }))
                }
                other => panic!("unexpected first print body: {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_integer_modulo_and_bitwise_ops() {
        let script = r#"
trace foo {
    let value = 0x1 | 0x2 ^ 0x3 & 0x4 << 0x1 + 0x2 % 0x3;
    let inverse = ~value;
}
"#;
        let prog = parse(script).expect("integer and bitwise ops should parse");
        let Statement::TracePoint { body, .. } = prog.statements.first().expect("trace") else {
            panic!("expected trace point");
        };
        let Statement::VarDeclaration { value, .. } = &body[0] else {
            panic!("expected var declaration");
        };
        let Expr::BinaryOp { op, left, right } = value else {
            panic!("expected bitwise-or root");
        };
        assert_eq!(*op, BinaryOp::BitOr);
        assert!(matches!(left.as_ref(), Expr::Int(1)));
        assert!(matches!(
            right.as_ref(),
            Expr::BinaryOp {
                op: BinaryOp::BitXor,
                ..
            }
        ));
        assert!(matches!(
            &body[1],
            Statement::VarDeclaration {
                value: Expr::UnaryBitNot(_),
                ..
            }
        ));
    }

    #[test]
    fn parse_array_index_accepts_constant_negative_literal() {
        let script = r#"
trace foo {
    print arr[-0x1];
    print obj.arr[0b10 - 0x3];
}
"#;
        let prog = parse(script).expect("parse ok");
        let trace = prog.statements.first().expect("trace");
        match trace {
            Statement::TracePoint { body, .. } => {
                match &body[0] {
                    Statement::Print(PrintStatement::ComplexVariable(Expr::ArrayAccess(
                        _,
                        index,
                    ))) => {
                        assert!(matches!(index.as_ref(), Expr::Int(-1)));
                    }
                    other => panic!("unexpected first print body: {other:?}"),
                }
                match &body[1] {
                    Statement::Print(PrintStatement::ComplexVariable(Expr::ArrayAccess(
                        _,
                        index,
                    ))) => {
                        assert!(matches!(index.as_ref(), Expr::Int(-1)));
                    }
                    other => panic!("unexpected second print body: {other:?}"),
                }
            }
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_print_format_arg_mismatch_reports_error() {
        // format_expr form
        let s1 = r#"
trace foo {
    print "A {} {}", x;
}
"#;
        let r1 = parse(s1);
        match r1 {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("expects 2 argument(s)"), "unexpected: {msg}");
            }
            other => panic!("expected TypeError from format arg mismatch, got {other:?}"),
        }

        // flattened string + args form
        let s2 = r#"
trace foo {
    print "B {} {}", y;
}
"#;
        let r2 = parse(s2);
        match r2 {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("expects 2 argument(s)"));
            }
            other => panic!("expected TypeError from format arg mismatch, got {other:?}"),
        }
    }

    #[test]
    fn parse_print_invalid_format_specifier_errors() {
        // Missing ':' prefix inside { }
        let s1 = r#"
trace foo { print "Bad {x}", 1; }
"#;
        let r1 = parse(s1);
        match r1 {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("Invalid format specifier"), "{msg}");
            }
            other => panic!("expected TypeError, got {other:?}"),
        }

        // Unsupported conversion {:q}
        let s2 = r#"
trace foo { print "Bad {:q}", 1; }
"#;
        let r2 = parse(s2);
        match r2 {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("Unsupported format conversion"), "{msg}");
            }
            other => panic!("expected TypeError, got {other:?}"),
        }
    }

    #[test]
    fn parse_hex_with_tab_is_rejected() {
        let s = r#"
trace foo {
    if memcmp(&buf[0], hex("50\t4f"), 2) { print "X"; }
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::TypeError(msg)) => {
                assert!(msg.contains("non-hex character"), "{msg}");
            }
            other => panic!("expected TypeError for tab in hex literal, got {other:?}"),
        }
    }

    #[test]
    fn parse_starts_with_constant_folds_on_literals() {
        let s = r#"
trace foo {
    if starts_with("abcdef", "abc") { print "T"; } else { print "F"; }
}
"#;
        let prog = parse(s).expect("parse ok");
        let stmt0 = prog.statements.first().expect("trace");
        match stmt0 {
            Statement::TracePoint { body, .. } => match &body[0] {
                Statement::If { condition, .. } => {
                    assert!(matches!(condition, Expr::Bool(true)));
                }
                other => panic!("expected If, got {other:?}"),
            },
            other => panic!("expected TracePoint, got {other:?}"),
        }
    }

    #[test]
    fn parse_backtrace_and_bt_statements() {
        let s = r#"
	trace foo {
	    backtrace;
	    bt;
	    bt raw;
	    bt full noinline;
	}
	"#;
        let program = parse(s).expect("parse ok");
        let Statement::TracePoint { body, .. } = &program.statements[0] else {
            panic!("expected trace");
        };
        assert_eq!(body.len(), 4);
        match &body[2] {
            Statement::Backtrace(bt) => {
                assert!(bt.raw);
                assert!(bt.inline);
            }
            other => panic!("expected backtrace, got {other:?}"),
        }
        match &body[3] {
            Statement::Backtrace(bt) => {
                assert!(bt.full);
                assert!(!bt.inline);
            }
            other => panic!("expected backtrace, got {other:?}"),
        }
    }

    #[test]
    fn parse_backtrace_rejects_named_depth_option() {
        let s = r#"
	trace foo {
	    bt depth=8;
	}
	"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("no longer a script option"), "{msg}");
                assert!(msg.contains("--backtrace-depth"), "{msg}");
            }
            other => panic!("expected SyntaxError, got {other:?}"),
        }
    }

    #[test]
    fn parse_backtrace_rejects_positional_depth_option() {
        let s = r#"
	trace foo {
	    bt 4 raw;
	}
	"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("no longer a script option"), "{msg}");
            }
            other => panic!("expected SyntaxError, got {other:?}"),
        }
    }

    #[test]
    fn parse_print_capture_len_suffix() {
        // {:s.name$} uses capture; does not consume extra arg
        let s = r#"
trace foo {
    let n = 3;
    print "tail={:s.n$}", p;
}
"#;
        let r = parse(s);
        assert!(r.is_ok(), "parse failed: {:?}", r.err());
    }

    #[test]
    fn parse_unknown_keyword_inside_trace_suggests_print() {
        let s = r#"
trace foo {
    pront "hello";
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(
                    msg.contains("Unknown keyword 'pront'"),
                    "unexpected msg: {msg}"
                );
                assert!(
                    msg.contains("Did you mean 'print'"),
                    "no suggestion in msg: {msg}"
                );
            }
            other => panic!("expected friendly SyntaxError for unknown keyword, got {other:?}"),
        }
    }

    #[test]
    fn parse_unknown_keyword_same_line_after_brace_suggests_print() {
        // Unknown keyword immediately after '{' on the same line
        let s = r#"trace foo {pirnt \"sa\";}"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(
                    msg.contains("Unknown keyword 'pirnt'"),
                    "unexpected msg: {msg}"
                );
                assert!(
                    msg.contains("Did you mean 'print'"),
                    "no suggestion in msg: {msg}"
                );
            }
            other => {
                panic!("expected friendly SyntaxError for same-line unknown keyword, got {other:?}")
            }
        }
    }

    #[test]
    fn parse_unknown_top_level_keyword_suggests_trace() {
        let s = r#"
traec bar {
    print "x";
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(
                    msg.contains("Unknown keyword 'traec'"),
                    "unexpected msg: {msg}"
                );
                assert!(
                    msg.contains("Did you mean 'trace'"),
                    "no suggestion in msg: {msg}"
                );
            }
            other => panic!("expected friendly SyntaxError for unknown keyword, got {other:?}"),
        }
    }

    #[test]
    fn parse_builtin_then_misspelled_keyword_should_point_to_misspell() {
        // Ensure builtin calls are not flagged; the real typo should be reported
        let s = r#"
trace foo {
    starts_with("a", "b"); prnit "oops";
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(
                    msg.contains("prnit"),
                    "should point to misspelled 'prnit': {msg}"
                );
                assert!(
                    !msg.contains("starts_with"),
                    "should not flag builtin call: {msg}"
                );
            }
            other => panic!("expected friendly SyntaxError for misspelled print, got {other:?}"),
        }
    }

    #[test]
    fn parse_misspelled_builtin_suggests_starts_with() {
        // Misspelled builtin should suggest the correct builtin name
        let s = r#"
trace foo {
    starst_with("a", "b");
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("Unknown keyword 'starst_with'"), "{msg}");
                assert!(msg.contains("Did you mean 'starts_with'"), "{msg}");
            }
            other => panic!("expected friendly suggestion for misspelled builtin, got {other:?}"),
        }
    }

    #[test]
    fn parse_misspelled_builtin_suggests_memcmp() {
        let s = r#"
trace foo {
    memcpm(&buf[0], &buf[1], 16);
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("Unknown keyword 'memcpm'"), "{msg}");
                assert!(msg.contains("Did you mean 'memcmp'"), "{msg}");
            }
            other => panic!("expected friendly suggestion for misspelled builtin, got {other:?}"),
        }
    }

    #[test]
    fn parse_if_condition_misspelled_builtin_suggests() {
        let s = r#"
trace foo {
    if starst_with("a", "b") { print "ok"; }
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("Unknown keyword 'starst_with'"), "{msg}");
                assert!(msg.contains("Did you mean 'starts_with'"), "{msg}");
            }
            other => panic!("expected friendly suggestion inside if(), got {other:?}"),
        }
    }

    #[test]
    fn parse_else_if_condition_misspelled_builtin_suggests() {
        let s = r#"
trace foo {
    if 1 { print "a"; } else if starst_with("a", "b") { print "b"; }
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(msg.contains("Unknown keyword 'starst_with'"), "{msg}");
                assert!(msg.contains("Did you mean 'starts_with'"), "{msg}");
            }
            other => panic!("expected friendly suggestion inside else if(), got {other:?}"),
        }
    }
    #[test]
    fn parse_unknown_keyword_generic_expected_list() {
        let s = r#"
foobarbaz {
    print "x";
}
"#;
        let r = parse(s);
        match r {
            Err(ParseError::SyntaxError(msg)) => {
                assert!(
                    msg.contains("Unknown keyword 'foobarbaz'"),
                    "unexpected msg: {msg}"
                );
                assert!(
                    msg.contains("Expected one of"),
                    "missing expected list in msg: {msg}"
                );
            }
            other => panic!("expected friendly SyntaxError with expected list, got {other:?}"),
        }
    }
}