mq-lang 0.6.0

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

use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;

use crate::{
    Ident, IdentWithToken, Shared,
    ast::{
        Program, TokenId,
        node::{self as ast, Args, Branches, Literal, MatchArm, MatchArms, Params, Pattern, StringSegment},
    },
    selector::Selector,
};

/// SmallVec-backed `(Ident, Literal)` map used during let-literal propagation.
type LiteralEnv = SmallVec<[(Ident, Literal); 8]>;

fn env_get(env: &LiteralEnv, key: Ident) -> Option<&Literal> {
    env.iter().rev().find(|(k, _)| *k == key).map(|(_, v)| v)
}

fn env_insert(env: &mut LiteralEnv, key: Ident, val: Literal) {
    if let Some(entry) = env.iter_mut().find(|(k, _)| *k == key) {
        entry.1 = val;
    } else {
        env.push((key, val));
    }
}

fn env_remove(env: &mut LiteralEnv, key: Ident) {
    env.retain(|(k, _)| *k != key);
}

/// Pointer-equality helper that works for both `Rc` and `Arc` (the `sync` feature).
#[inline]
fn ptr_eq<T: ?Sized>(a: &Shared<T>, b: &Shared<T>) -> bool {
    #[cfg(not(feature = "sync"))]
    {
        std::rc::Rc::ptr_eq(a, b)
    }
    #[cfg(feature = "sync")]
    {
        std::sync::Arc::ptr_eq(a, b)
    }
}

/// Controls which optimization passes are applied by the [`Optimizer`].
///
/// - `None` (default): no transformations; the AST is returned unchanged.
/// - `Basic`: constant folding, dead-branch elimination, and selector-chain merging.
/// - `Full`: all passes — `Basic` plus let-literal propagation, function inlining, and tail-call optimization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OptimizationLevel {
    #[default]
    None,
    Basic,
    Full,
}

/// Map `program` through `f` without allocating a new `Vec` when no node changes.
///
/// If every node is pointer-equal after `f`, the original `program` is returned as-is.
/// Only when a changed node is encountered does a new `Vec` get allocated, pre-seeded with
/// the unchanged prefix already seen.
fn lazy_map_program<F>(program: Program, mut f: F) -> Program
where
    F: FnMut(&Shared<ast::Node>) -> Shared<ast::Node>,
{
    let mut result: Option<Vec<Shared<ast::Node>>> = None;
    for (i, node) in program.iter().enumerate() {
        let opt = f(node);
        if !ptr_eq(&opt, node) {
            if result.is_none() {
                let mut r = Vec::with_capacity(program.len());
                r.extend(program[..i].iter().cloned());
                result = Some(r);
            }
            result.as_mut().unwrap().push(opt);
        } else if let Some(ref mut r) = result {
            r.push(Shared::clone(node));
        }
    }
    result.unwrap_or(program)
}

/// AST optimizer that applies safe, semantics-preserving transformations before evaluation.
#[derive(Default)]
pub struct Optimizer {
    level: OptimizationLevel,
}

impl Optimizer {
    /// Creates an `Optimizer` that runs only the passes enabled by `level`.
    pub fn with_level(level: OptimizationLevel) -> Self {
        Self { level }
    }

    /// Runs all enabled optimization passes on `program` and returns the transformed AST.
    pub fn optimize(&self, program: Program) -> Program {
        self.optimize_impl(program, true)
    }

    /// Optimize a nested sub-program (body of a Def, Block, While, Loop, Foreach, etc.).
    fn optimize_nested(&self, program: Program, parent_user_defs: &FxHashSet<Ident>) -> Program {
        if matches!(self.level, OptimizationLevel::None) {
            return program;
        }

        // Merge parent user_defs with any local Defs. When there are no local Defs (the
        // common case for loop bodies and blocks), skip the allocation entirely.
        let merged;
        let user_defs: &FxHashSet<Ident> = if program.iter().any(|n| matches!(&*n.expr, ast::Expr::Def(..))) {
            merged = parent_user_defs
                .iter()
                .copied()
                .chain(program.iter().filter_map(|n| {
                    if let ast::Expr::Def(ident, ..) = &*n.expr {
                        Some(ident.name)
                    } else {
                        None
                    }
                }))
                .collect();
            &merged
        } else {
            parent_user_defs
        };

        let optimized = lazy_map_program(program, |n| self.optimize_node(Shared::clone(n), user_defs));
        self.merge_selector_chains(optimized)
    }

    /// Internal optimization entry point.
    fn optimize_impl(&self, program: Program, top_level: bool) -> Program {
        // Collect user-defined function names only when Def nodes are actually present.
        // Programs without any `def` (the common case for simple queries) share a static
        // empty set — no heap allocation.
        static EMPTY_DEFS: OnceLock<FxHashSet<Ident>> = OnceLock::new();
        let user_defs_owned: FxHashSet<Ident>;
        let user_defs: &FxHashSet<Ident> = if program.iter().any(|n| matches!(&*n.expr, ast::Expr::Def(..))) {
            user_defs_owned = program
                .iter()
                .filter_map(|n| {
                    if let ast::Expr::Def(ident, ..) = &*n.expr {
                        Some(ident.name)
                    } else {
                        None
                    }
                })
                .collect();
            &user_defs_owned
        } else {
            EMPTY_DEFS.get_or_init(FxHashSet::default)
        };

        match self.level {
            OptimizationLevel::None => program,
            OptimizationLevel::Basic => {
                let optimized: Program = program
                    .into_iter()
                    .map(|node| self.optimize_node(node, user_defs))
                    .collect();
                self.merge_selector_chains(optimized)
            }
            OptimizationLevel::Full => {
                // Pass 1: constant folding + let-literal propagation in a single traversal.
                let program = self.propagate_and_fold(program, user_defs);
                let program = self.merge_selector_chains(program);

                // Passes 2-4 are only worthwhile when Def nodes are present.
                if !program.iter().any(|n| matches!(&*n.expr, ast::Expr::Def(..))) {
                    return program;
                }

                let inlinable = collect_inlinable(&program);
                let program: Program = if inlinable.is_empty() {
                    program
                } else {
                    program.into_iter().map(|n| self.apply_inline(n, &inlinable)).collect()
                };
                let program = apply_tco_transforms(program);
                // Dead-def elimination is safe only at the top level where all call sites
                // are visible. In nested scopes, external callers are not in scope.
                let program = if top_level {
                    eliminate_dead_defs(program, &inlinable)
                } else {
                    program
                };
                let refolded: Program = program.into_iter().map(|n| self.optimize_node(n, user_defs)).collect();
                self.merge_selector_chains(refolded)
            }
        }
    }

    /// Single-pass constant folding + let-literal propagation.
    ///
    /// Processes top-level nodes left-to-right:
    /// - `let x = <foldable-expr>`: optimises the RHS, registers `x` in the substitution
    ///   map if the result is a literal.
    /// - All other nodes: substitute known literals, then fold constants.
    fn propagate_and_fold(&self, program: Program, user_defs: &FxHashSet<Ident>) -> Program {
        let has_let_literal = program.iter().any(|n| {
            matches!(&*n.expr, ast::Expr::Let(Pattern::Ident(_), rhs) if matches!(&*rhs.expr, ast::Expr::Literal(_)))
        });

        if !has_let_literal {
            return lazy_map_program(program, |n| self.optimize_node(Shared::clone(n), user_defs));
        }

        let mut env: LiteralEnv = LiteralEnv::new();
        let mut result: Program = Vec::with_capacity(program.len());

        for node in program {
            let token_id = node.token_id;
            match &*node.expr {
                ast::Expr::Let(Pattern::Ident(ident), rhs) => {
                    let opt_rhs = self.optimize_node(Shared::clone(rhs), user_defs);
                    if let ast::Expr::Literal(lit) = &*opt_rhs.expr {
                        env_insert(&mut env, ident.name, lit.clone());
                    } else {
                        env_remove(&mut env, ident.name);
                    }
                    // Reuse the original node when the RHS didn't change (e.g., already a literal).
                    if ptr_eq(&opt_rhs, rhs) {
                        result.push(node);
                    } else {
                        result.push(Shared::new(ast::Node {
                            token_id,
                            expr: Shared::new(ast::Expr::Let(Pattern::Ident(ident.clone()), opt_rhs)),
                        }));
                    }
                }
                _ => {
                    let optimized = if env.is_empty() {
                        self.optimize_node(node, user_defs)
                    } else {
                        self.optimize_node(self.substitute_literals(node, &env), user_defs)
                    };
                    result.push(optimized);
                }
            }
        }

        result
    }

    fn merge_selector_chains(&self, program: Program) -> Program {
        // Fast path: skip allocation when no consecutive Selector nodes exist.
        let has_consecutive = program
            .windows(2)
            .any(|w| matches!(&*w[0].expr, ast::Expr::Selector(_)) && matches!(&*w[1].expr, ast::Expr::Selector(_)));
        if !has_consecutive {
            return program;
        }

        let mut result: Program = Vec::with_capacity(program.len());
        let mut iter = program.into_iter().peekable();

        while let Some(node) = iter.next() {
            if let ast::Expr::Selector(sel) = &*node.expr {
                let token_id = node.token_id;
                let mut chain: SmallVec<[Selector; 4]> = SmallVec::new();
                chain.push(sel.clone());

                while let Some(next) = iter.peek() {
                    if let ast::Expr::Selector(next_sel) = &*next.expr {
                        chain.push(next_sel.clone());
                        iter.next();
                    } else {
                        break;
                    }
                }

                if chain.len() == 1 {
                    result.push(node);
                } else {
                    result.push(Shared::new(ast::Node {
                        token_id,
                        expr: Shared::new(ast::Expr::SelectorChain(chain)),
                    }));
                }
            } else {
                result.push(node);
            }
        }

        result
    }

    /// Substitute `Ident` references with their bound literals, without crossing scope boundaries.
    fn substitute_literals(&self, node: Shared<ast::Node>, env: &LiteralEnv) -> Shared<ast::Node> {
        if env.is_empty() {
            return node;
        }
        let token_id = node.token_id;

        match &*node.expr {
            ast::Expr::Ident(ident) => {
                if let Some(lit) = env_get(env, ident.name) {
                    return Shared::new(ast::Node {
                        token_id,
                        expr: Shared::new(ast::Expr::Literal(lit.clone())),
                    });
                }
                node
            }
            ast::Expr::Call(ident, args) => {
                let subst_args: Args = args
                    .iter()
                    .map(|a| self.substitute_literals(Shared::clone(a), env))
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Call(ident.clone(), subst_args)),
                })
            }
            ast::Expr::CallDynamic(callable, args) => {
                let subst_callable = self.substitute_literals(Shared::clone(callable), env);
                let subst_args: Args = args
                    .iter()
                    .map(|a| self.substitute_literals(Shared::clone(a), env))
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::CallDynamic(subst_callable, subst_args)),
                })
            }
            ast::Expr::SelectorCall(selector, args) => {
                let subst_args: Args = args
                    .iter()
                    .map(|a| self.substitute_literals(Shared::clone(a), env))
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::SelectorCall(selector.clone(), subst_args)),
                })
            }
            ast::Expr::If(branches) => {
                let subst_branches: Branches = branches
                    .iter()
                    .map(|(cond, body)| {
                        (
                            cond.as_ref().map(|c| self.substitute_literals(Shared::clone(c), env)),
                            self.substitute_literals(Shared::clone(body), env),
                        )
                    })
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::If(subst_branches)),
                })
            }
            ast::Expr::And(operands) => {
                let subst: Vec<_> = operands
                    .iter()
                    .map(|o| self.substitute_literals(Shared::clone(o), env))
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::And(subst)),
                })
            }
            ast::Expr::Or(operands) => {
                let subst: Vec<_> = operands
                    .iter()
                    .map(|o| self.substitute_literals(Shared::clone(o), env))
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Or(subst)),
                })
            }
            ast::Expr::Paren(inner) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Paren(self.substitute_literals(Shared::clone(inner), env))),
            }),
            ast::Expr::Try(try_expr, catch_expr) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Try(
                    self.substitute_literals(Shared::clone(try_expr), env),
                    self.substitute_literals(Shared::clone(catch_expr), env),
                )),
            }),
            ast::Expr::Break(Some(val)) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Break(Some(
                    self.substitute_literals(Shared::clone(val), env),
                ))),
            }),
            // Substitute into Expr segments of interpolated strings so that
            // `let x = "hi" | s"${x}!"` can later be folded to `"hi!"`.
            ast::Expr::InterpolatedString(segments) => {
                let subst_segs: Vec<StringSegment> = segments
                    .iter()
                    .map(|seg| match seg {
                        StringSegment::Expr(inner) => {
                            StringSegment::Expr(self.substitute_literals(Shared::clone(inner), env))
                        }
                        other => other.clone(),
                    })
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::InterpolatedString(subst_segs)),
                })
            }
            // Scope-creating or leaf nodes: stop substitution here.
            ast::Expr::Block(_)
            | ast::Expr::Def(_, _, _)
            | ast::Expr::Fn(_, _)
            | ast::Expr::While(_, _)
            | ast::Expr::Loop(_)
            | ast::Expr::Foreach(_, _, _)
            | ast::Expr::Let(_, _)
            | ast::Expr::Var(_, _)
            | ast::Expr::As(_, _)
            | ast::Expr::Assign(_, _)
            | ast::Expr::Match(_, _)
            | ast::Expr::Literal(_)
            | ast::Expr::Selector(_)
            | ast::Expr::SelectorChain(_)
            | ast::Expr::Self_
            | ast::Expr::Nodes
            | ast::Expr::Break(None)
            | ast::Expr::Continue
            | ast::Expr::Include(_)
            | ast::Expr::Import(_)
            | ast::Expr::Module(_, _)
            | ast::Expr::Macro(_, _, _)
            | ast::Expr::Quote(_)
            | ast::Expr::Unquote(_)
            | ast::Expr::QualifiedAccess(_, _) => node,
        }
    }

    fn apply_inline(&self, node: Shared<ast::Node>, fns: &FxHashMap<Ident, InlinableFn>) -> Shared<ast::Node> {
        if fns.is_empty() {
            return node;
        }
        let token_id = node.token_id;

        match &*node.expr {
            ast::Expr::Call(ident, args) => {
                let opt_args: Args = args.iter().map(|a| self.apply_inline(Shared::clone(a), fns)).collect();

                if let Some(f) = fns.get(&ident.name).filter(|f| opt_args.len() == f.params.len()) {
                    return substitute_params(Shared::clone(&f.body), &f.params, &opt_args, token_id);
                }

                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Call(ident.clone(), opt_args)),
                })
            }
            // Recurse into sub-expressions — but not across scope-creating nodes (Def, Fn, Block).
            ast::Expr::If(branches) => {
                let branches: ast::Branches = branches
                    .iter()
                    .map(|(cond, body)| {
                        (
                            cond.as_ref().map(|c| self.apply_inline(Shared::clone(c), fns)),
                            self.apply_inline(Shared::clone(body), fns),
                        )
                    })
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::If(branches)),
                })
            }
            ast::Expr::And(ops) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::And(
                    ops.iter().map(|o| self.apply_inline(Shared::clone(o), fns)).collect(),
                )),
            }),
            ast::Expr::Or(ops) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Or(
                    ops.iter().map(|o| self.apply_inline(Shared::clone(o), fns)).collect(),
                )),
            }),
            ast::Expr::Try(try_expr, catch_expr) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Try(
                    self.apply_inline(Shared::clone(try_expr), fns),
                    self.apply_inline(Shared::clone(catch_expr), fns),
                )),
            }),
            ast::Expr::SelectorCall(sel, args) => {
                let opt_args: Args = args.iter().map(|a| self.apply_inline(Shared::clone(a), fns)).collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::SelectorCall(sel.clone(), opt_args)),
                })
            }
            // Scope-creating and leaf nodes are left unchanged.
            _ => node,
        }
    }

    fn optimize_node(&self, node: Shared<ast::Node>, user_defs: &FxHashSet<Ident>) -> Shared<ast::Node> {
        let token_id = node.token_id;

        match &*node.expr {
            ast::Expr::Paren(inner) => self.optimize_node(Shared::clone(inner), user_defs),
            ast::Expr::Call(ident, args) => {
                let opt_args: Args = args
                    .iter()
                    .map(|a| self.optimize_node(Shared::clone(a), user_defs))
                    .collect();
                if let Some(folded) = self.try_fold_call(token_id, &ident.name, &opt_args, user_defs) {
                    return folded;
                }
                // Return the original node when no argument changed (avoids allocation).
                if args.iter().zip(opt_args.iter()).all(|(orig, opt)| ptr_eq(orig, opt)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Call(ident.clone(), opt_args)),
                })
            }
            ast::Expr::If(branches) => self.optimize_if(token_id, branches, user_defs),
            ast::Expr::And(operands) => self.optimize_and(token_id, operands, user_defs),
            ast::Expr::Or(operands) => self.optimize_or(token_id, operands, user_defs),
            ast::Expr::Block(program) => {
                let opt = self.optimize_nested(program.clone(), user_defs);
                if program.iter().zip(opt.iter()).all(|(a, b)| ptr_eq(a, b)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Block(opt)),
                })
            }
            ast::Expr::Def(ident, params, program) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Def(
                    ident.clone(),
                    self.optimize_params(params, user_defs),
                    self.optimize_nested(program.clone(), user_defs),
                )),
            }),
            ast::Expr::Fn(params, program) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Fn(
                    self.optimize_params(params, user_defs),
                    self.optimize_nested(program.clone(), user_defs),
                )),
            }),
            ast::Expr::While(cond, program) => {
                let opt_cond = self.optimize_node(Shared::clone(cond), user_defs);
                let opt_body = self.optimize_nested(program.clone(), user_defs);
                if ptr_eq(&opt_cond, cond) && program.iter().zip(opt_body.iter()).all(|(a, b)| ptr_eq(a, b)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::While(opt_cond, opt_body)),
                })
            }
            ast::Expr::Loop(program) => {
                let opt = self.optimize_nested(program.clone(), user_defs);
                if program.iter().zip(opt.iter()).all(|(a, b)| ptr_eq(a, b)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Loop(opt)),
                })
            }
            ast::Expr::Foreach(ident, values, program) => {
                let opt_values = self.optimize_node(Shared::clone(values), user_defs);
                let opt_body = self.optimize_nested(program.clone(), user_defs);
                if ptr_eq(&opt_values, values) && program.iter().zip(opt_body.iter()).all(|(a, b)| ptr_eq(a, b)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Foreach(ident.clone(), opt_values, opt_body)),
                })
            }
            ast::Expr::As(ident, inner) => {
                let opt_inner = self.optimize_node(Shared::clone(inner), user_defs);
                if ptr_eq(&opt_inner, inner) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::As(ident.clone(), opt_inner)),
                })
            }
            ast::Expr::Let(pattern, inner) => {
                let opt_inner = self.optimize_node(Shared::clone(inner), user_defs);
                if ptr_eq(&opt_inner, inner) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Let(pattern.clone(), opt_inner)),
                })
            }
            ast::Expr::Var(pattern, inner) => {
                let opt_inner = self.optimize_node(Shared::clone(inner), user_defs);
                if ptr_eq(&opt_inner, inner) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Var(pattern.clone(), opt_inner)),
                })
            }
            ast::Expr::Assign(ident, inner) => {
                let opt_inner = self.optimize_node(Shared::clone(inner), user_defs);
                if ptr_eq(&opt_inner, inner) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Assign(ident.clone(), opt_inner)),
                })
            }
            ast::Expr::Try(try_expr, catch_expr) => {
                let opt_try = self.optimize_node(Shared::clone(try_expr), user_defs);
                let opt_catch = self.optimize_node(Shared::clone(catch_expr), user_defs);
                if ptr_eq(&opt_try, try_expr) && ptr_eq(&opt_catch, catch_expr) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Try(opt_try, opt_catch)),
                })
            }
            ast::Expr::Break(Some(val)) => {
                let opt_val = self.optimize_node(Shared::clone(val), user_defs);
                if ptr_eq(&opt_val, val) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Break(Some(opt_val))),
                })
            }
            ast::Expr::Match(value_node, arms) => {
                let opt_value = self.optimize_node(Shared::clone(value_node), user_defs);
                let opt_arms: MatchArms = arms
                    .iter()
                    .map(|arm| MatchArm {
                        pattern: arm.pattern.clone(),
                        guard: arm
                            .guard
                            .as_ref()
                            .map(|g| self.optimize_node(Shared::clone(g), user_defs)),
                        body: self.optimize_node(Shared::clone(&arm.body), user_defs),
                    })
                    .collect();
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::Match(opt_value, opt_arms)),
                })
            }
            ast::Expr::CallDynamic(callable, args) => {
                let opt_callable = self.optimize_node(Shared::clone(callable), user_defs);
                let opt_args: Args = args
                    .iter()
                    .map(|a| self.optimize_node(Shared::clone(a), user_defs))
                    .collect();
                if ptr_eq(&opt_callable, callable)
                    && args.iter().zip(opt_args.iter()).all(|(orig, opt)| ptr_eq(orig, opt))
                {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::CallDynamic(opt_callable, opt_args)),
                })
            }
            ast::Expr::SelectorCall(selector, args) => {
                let opt_args: Args = args
                    .iter()
                    .map(|a| self.optimize_node(Shared::clone(a), user_defs))
                    .collect();
                if args.iter().zip(opt_args.iter()).all(|(orig, opt)| ptr_eq(orig, opt)) {
                    return node;
                }
                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::SelectorCall(selector.clone(), opt_args)),
                })
            }
            ast::Expr::InterpolatedString(segments) => {
                // Optimize each Expr segment; also promote string-literal Expr segments to
                // Text so that fully-constant interpolated strings can be folded.
                let opt_segs: Vec<StringSegment> = segments
                    .iter()
                    .map(|seg| match seg {
                        StringSegment::Expr(n) => {
                            let opt = self.optimize_node(Shared::clone(n), user_defs);
                            if let ast::Expr::Literal(Literal::String(s)) = &*opt.expr {
                                StringSegment::Text(s.clone())
                            } else {
                                StringSegment::Expr(opt)
                            }
                        }
                        other => other.clone(),
                    })
                    .collect();

                if opt_segs.iter().all(|s| matches!(s, StringSegment::Text(_))) {
                    let folded = opt_segs.iter().fold(String::new(), |mut acc, s| {
                        if let StringSegment::Text(t) = s {
                            acc.push_str(t);
                        }
                        acc
                    });
                    return Shared::new(ast::Node {
                        token_id,
                        expr: Shared::new(ast::Expr::Literal(Literal::String(folded))),
                    });
                }

                Shared::new(ast::Node {
                    token_id,
                    expr: Shared::new(ast::Expr::InterpolatedString(opt_segs)),
                })
            }
            ast::Expr::Module(ident, program) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Module(
                    ident.clone(),
                    self.optimize_nested(program.clone(), user_defs),
                )),
            }),
            ast::Expr::Unquote(inner) => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Unquote(self.optimize_node(Shared::clone(inner), user_defs))),
            }),
            ast::Expr::Literal(_)
            | ast::Expr::Ident(_)
            | ast::Expr::Selector(_)
            | ast::Expr::SelectorChain(_)
            | ast::Expr::Self_
            | ast::Expr::Nodes
            | ast::Expr::Break(None)
            | ast::Expr::Continue
            | ast::Expr::Include(_)
            | ast::Expr::Import(_)
            | ast::Expr::Macro(_, _, _)
            | ast::Expr::Quote(_)
            | ast::Expr::QualifiedAccess(_, _) => node,
        }
    }

    fn try_fold_call(
        &self,
        token_id: TokenId,
        name: &crate::Ident,
        args: &Args,
        user_defs: &FxHashSet<Ident>,
    ) -> Option<Shared<ast::Node>> {
        use crate::ast::constants::builtins;

        // Never fold a call whose name is shadowed by a user-defined function.
        if user_defs.contains(name) {
            return None;
        }

        let make_lit = |lit: Literal| {
            Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Literal(lit)),
            })
        };

        if args.len() == 2 {
            let lhs_lit = literal_of(&args[0]);
            let rhs_lit = literal_of(&args[1]);

            if let (Some(lhs), Some(rhs)) = (lhs_lit.clone(), rhs_lit.clone()) {
                match name.as_str().as_str() {
                    n @ (builtins::ADD | builtins::SUB | builtins::MUL | builtins::DIV | builtins::MOD) => {
                        match (lhs, rhs) {
                            (Literal::Number(a), Literal::Number(b)) => {
                                if (n == builtins::DIV || n == builtins::MOD) && b.is_zero() {
                                    return None;
                                }
                                let result = match n {
                                    builtins::ADD => a + b,
                                    builtins::SUB => a - b,
                                    builtins::MUL => a * b,
                                    builtins::DIV => a / b,
                                    builtins::MOD => a % b,
                                    _ => unreachable!(),
                                };
                                return Some(make_lit(Literal::Number(result)));
                            }
                            (Literal::String(a), Literal::String(b)) if n == builtins::ADD => {
                                return Some(make_lit(Literal::String(a + &b)));
                            }
                            _ => {}
                        }
                    }

                    builtins::EQ => return Some(make_lit(Literal::Bool(literal_eq(lhs, rhs)))),
                    builtins::NE => return Some(make_lit(Literal::Bool(!literal_eq(lhs, rhs)))),

                    n @ (builtins::LT | builtins::LTE | builtins::GT | builtins::GTE) => match (lhs, rhs) {
                        (Literal::Number(a), Literal::Number(b)) => {
                            if a.is_nan() || b.is_nan() {
                                return None;
                            }
                            let result = match n {
                                builtins::LT => a < b,
                                builtins::LTE => a <= b,
                                builtins::GT => a > b,
                                builtins::GTE => a >= b,
                                _ => unreachable!(),
                            };
                            return Some(make_lit(Literal::Bool(result)));
                        }
                        (Literal::String(a), Literal::String(b)) => {
                            let result = match n {
                                builtins::LT => a < b,
                                builtins::LTE => a <= b,
                                builtins::GT => a > b,
                                builtins::GTE => a >= b,
                                _ => unreachable!(),
                            };
                            return Some(make_lit(Literal::Bool(result)));
                        }
                        _ => {}
                    },

                    builtins::STARTS_WITH => {
                        if let (Literal::String(s), Literal::String(prefix)) = (lhs, rhs) {
                            return Some(make_lit(Literal::Bool(s.starts_with(&*prefix))));
                        }
                    }

                    builtins::ENDS_WITH => {
                        if let (Literal::String(s), Literal::String(suffix)) = (lhs, rhs) {
                            return Some(make_lit(Literal::Bool(s.ends_with(&*suffix))));
                        }
                    }

                    builtins::INDEX => {
                        if let (Literal::String(s), Literal::String(sub)) = (lhs, rhs) {
                            let pos = s.find(&*sub).map(|v| v as i64).unwrap_or(-1);
                            return Some(make_lit(Literal::Number(pos.into())));
                        }
                    }

                    builtins::RINDEX => {
                        if let (Literal::String(s), Literal::String(sub)) = (lhs, rhs) {
                            let pos = s.rfind(&*sub).map(|v| v as i64).unwrap_or(-1);
                            return Some(make_lit(Literal::Number(pos.into())));
                        }
                    }

                    builtins::COALESCE => {
                        return Some(match lhs {
                            Literal::None => Shared::clone(&args[1]),
                            _ => Shared::clone(&args[0]),
                        });
                    }

                    _ => {}
                }
            }

            // Partial fold: coalesce(none, x) → x even when x is not a literal.
            if name.as_str().as_str() == builtins::COALESCE {
                if matches!(&lhs_lit, Some(Literal::None)) {
                    return Some(Shared::clone(&args[1]));
                }
                if lhs_lit.as_ref().is_some_and(|lit| !matches!(lit, Literal::None)) {
                    return Some(Shared::clone(&args[0]));
                }
            }

            // One operand is a literal: algebraic identity folding.
            let op = name.as_str();
            match op.as_str() {
                builtins::ADD => {
                    // add(x, 0) → x, add(0, x) → x
                    if matches!(&rhs_lit, Some(Literal::Number(n)) if n.is_zero()) {
                        return Some(Shared::clone(&args[0]));
                    }
                    if matches!(&lhs_lit, Some(Literal::Number(n)) if n.is_zero()) {
                        return Some(Shared::clone(&args[1]));
                    }
                    // add("", x) → x, add(x, "") → x
                    if matches!(&rhs_lit, Some(Literal::String(s)) if s.is_empty()) {
                        return Some(Shared::clone(&args[0]));
                    }
                    if matches!(&lhs_lit, Some(Literal::String(s)) if s.is_empty()) {
                        return Some(Shared::clone(&args[1]));
                    }
                }
                builtins::SUB => {
                    // sub(x, 0) → x
                    if matches!(&rhs_lit, Some(Literal::Number(n)) if n.is_zero()) {
                        return Some(Shared::clone(&args[0]));
                    }
                }
                builtins::MUL => {
                    // mul(x, 1) → x, mul(1, x) → x
                    if matches!(&rhs_lit, Some(Literal::Number(n)) if is_one(n)) {
                        return Some(Shared::clone(&args[0]));
                    }
                    if matches!(&lhs_lit, Some(Literal::Number(n)) if is_one(n)) {
                        return Some(Shared::clone(&args[1]));
                    }
                    // mul(x, 0) → 0, mul(0, x) → 0
                    if matches!(&rhs_lit, Some(Literal::Number(n)) if n.is_zero()) {
                        return Some(make_lit(Literal::Number(0i64.into())));
                    }
                    if matches!(&lhs_lit, Some(Literal::Number(n)) if n.is_zero()) {
                        return Some(make_lit(Literal::Number(0i64.into())));
                    }
                }
                builtins::DIV => {
                    // div(x, 1) → x
                    if matches!(&rhs_lit, Some(Literal::Number(n)) if is_one(n)) {
                        return Some(Shared::clone(&args[0]));
                    }
                }
                _ => {}
            }
        }

        if args.len() == 1 {
            let arg = literal_of(&args[0])?;
            match name.as_str().as_str() {
                builtins::NOT => {
                    if let Literal::Bool(b) = arg {
                        return Some(make_lit(Literal::Bool(!b)));
                    }
                }
                builtins::NEGATE => {
                    if let Literal::Number(n) = arg {
                        return Some(make_lit(Literal::Number(-n)));
                    }
                }
                // Numeric rounding/absolute value — safe because these are total functions on numbers.
                n @ (builtins::FLOOR | builtins::CEIL | builtins::ROUND | builtins::ABS | builtins::TRUNC) => {
                    if let Literal::Number(num) = arg {
                        if num.is_nan() {
                            return None;
                        }
                        let result = match n {
                            builtins::FLOOR => num.value().floor(),
                            builtins::CEIL => num.value().ceil(),
                            builtins::ROUND => num.value().round(),
                            builtins::ABS => num.value().abs(),
                            builtins::TRUNC => num.value().trunc(),
                            _ => unreachable!(),
                        };
                        return Some(make_lit(Literal::Number(result.into())));
                    }
                }
                builtins::LEN => match arg {
                    Literal::String(s) => return Some(make_lit(Literal::Number(s.chars().count().into()))),
                    Literal::Bytes(b) => return Some(make_lit(Literal::Number(b.len().into()))),
                    _ => {}
                },
                // to_string on any primitive literal — replicates the runtime behaviour exactly.
                builtins::TO_STRING => {
                    let s = match arg {
                        Literal::String(s) => s,
                        Literal::Number(n) => n.to_string(),
                        Literal::Bool(b) => b.to_string(),
                        Literal::None => String::new(),
                        Literal::Symbol(sym) => sym.to_string(),
                        Literal::Bytes(_) => return None, // hex encoding would need extra logic
                    };
                    return Some(make_lit(Literal::String(s)));
                }
                // to_number on a string literal — only fold when parsing succeeds.
                builtins::TO_NUMBER => {
                    if let Literal::String(s) = arg {
                        return s.parse::<f64>().ok().map(|n| make_lit(Literal::Number(n.into())));
                    }
                }
                n @ (builtins::TRIM | builtins::LTRIM | builtins::RTRIM) => {
                    if let Literal::String(s) = arg {
                        let result = match n {
                            builtins::TRIM => s.trim().to_string(),
                            builtins::LTRIM => s.trim_start().to_string(),
                            builtins::RTRIM => s.trim_end().to_string(),
                            _ => unreachable!(),
                        };
                        return Some(make_lit(Literal::String(result)));
                    }
                }
                n @ (builtins::UPCASE | builtins::DOWNCASE) => {
                    if let Literal::String(s) = arg {
                        let result = match n {
                            builtins::UPCASE => s.to_uppercase(),
                            builtins::DOWNCASE => s.to_lowercase(),
                            _ => unreachable!(),
                        };
                        return Some(make_lit(Literal::String(result)));
                    }
                }

                _ => {}
            }
        }

        if args.len() == 3 {
            let a = literal_of(&args[0]);
            let b = literal_of(&args[1]);
            let c = literal_of(&args[2]);
            if let (Some(Literal::String(s)), Some(Literal::String(from)), Some(Literal::String(to))) = (a, b, c) {
                // replace("foo", "o", "a") → "faa"
                if name.as_str().as_str() == builtins::REPLACE {
                    return Some(make_lit(Literal::String(s.replace(&*from, &to))));
                }
            }
        }

        None
    }

    fn optimize_if(&self, token_id: TokenId, branches: &Branches, user_defs: &FxHashSet<Ident>) -> Shared<ast::Node> {
        let mut remaining: Branches = SmallVec::new();

        for (cond_node, body_node) in branches {
            let opt_body = self.optimize_node(Shared::clone(body_node), user_defs);

            match cond_node {
                None => {
                    remaining.push((None, opt_body));
                    break;
                }
                Some(cond) => {
                    let opt_cond = self.optimize_node(Shared::clone(cond), user_defs);
                    match &*opt_cond.expr {
                        ast::Expr::Literal(Literal::Bool(true)) => {
                            remaining.push((None, opt_body));
                            break;
                        }
                        ast::Expr::Literal(Literal::Bool(false)) => {
                            continue;
                        }
                        _ => {
                            remaining.push((Some(opt_cond), opt_body));
                        }
                    }
                }
            }
        }

        match remaining.len() {
            0 => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Literal(Literal::None)),
            }),
            1 if remaining[0].0.is_none() => Shared::clone(&remaining[0].1),
            _ => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::If(remaining)),
            }),
        }
    }

    fn optimize_and(
        &self,
        token_id: TokenId,
        operands: &[Shared<ast::Node>],
        user_defs: &FxHashSet<Ident>,
    ) -> Shared<ast::Node> {
        let mut remaining: Vec<Shared<ast::Node>> = Vec::with_capacity(operands.len());

        for op in operands {
            let opt = self.optimize_node(Shared::clone(op), user_defs);
            match &*opt.expr {
                ast::Expr::Literal(lit) if !literal_is_truthy(lit) => {
                    return Shared::new(ast::Node {
                        token_id,
                        expr: Shared::new(ast::Expr::Literal(Literal::Bool(false))),
                    });
                }
                ast::Expr::Literal(lit) if literal_is_truthy(lit) => continue,
                _ => remaining.push(opt),
            }
        }

        match remaining.len() {
            0 => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Literal(Literal::Bool(true))),
            }),
            _ => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::And(remaining)),
            }),
        }
    }

    fn optimize_or(
        &self,
        token_id: TokenId,
        operands: &[Shared<ast::Node>],
        user_defs: &FxHashSet<Ident>,
    ) -> Shared<ast::Node> {
        let mut remaining: Vec<Shared<ast::Node>> = Vec::with_capacity(operands.len());

        for op in operands {
            let opt = self.optimize_node(Shared::clone(op), user_defs);
            match &*opt.expr {
                ast::Expr::Literal(lit) if literal_is_truthy(lit) => return opt,
                ast::Expr::Literal(lit) if !literal_is_truthy(lit) => continue,
                _ => remaining.push(opt),
            }
        }

        match remaining.len() {
            0 => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Literal(Literal::Bool(false))),
            }),
            _ => Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Or(remaining)),
            }),
        }
    }

    fn optimize_params(&self, params: &Params, user_defs: &FxHashSet<Ident>) -> Params {
        params
            .iter()
            .map(|p| ast::Param {
                ident: p.ident.clone(),
                default: p
                    .default
                    .as_ref()
                    .map(|d| self.optimize_node(Shared::clone(d), user_defs)),
                is_variadic: p.is_variadic,
            })
            .collect()
    }
}

struct InlinableFn {
    params: Vec<Ident>,
    body: Shared<ast::Node>,
}

/// Scan `program` for `Def` nodes whose bodies are safe to inline.
///
/// A function is inlineable when:
/// - Its body has exactly one node.
/// - It has no variadic or default-valued parameters.
/// - It is not self-recursive.
/// - Its body contains no free variables (all `Ident` refs are parameter names).
fn collect_inlinable(program: &Program) -> FxHashMap<Ident, InlinableFn> {
    let mut map = FxHashMap::default();
    for node in program {
        let ast::Expr::Def(ident, params, body) = &*node.expr else {
            continue;
        };
        if body.len() != 1 {
            continue;
        }
        if params.iter().any(|p| p.is_variadic || p.default.is_some()) {
            continue;
        }
        let body_node = &body[0];
        let param_names: Vec<Ident> = params.iter().map(|p| p.ident.name).collect();
        if has_recursion(body_node, ident.name) || has_free_vars(body_node, &param_names) {
            continue;
        }
        map.insert(
            ident.name,
            InlinableFn {
                params: param_names,
                body: Shared::clone(body_node),
            },
        );
    }
    map
}

/// Returns `true` if `node` contains a direct or indirect call to `fn_name`.
fn has_recursion(node: &Shared<ast::Node>, fn_name: Ident) -> bool {
    match &*node.expr {
        ast::Expr::Call(ident, args) => ident.name == fn_name || args.iter().any(|a| has_recursion(a, fn_name)),
        ast::Expr::Ident(ident) => ident.name == fn_name,
        ast::Expr::And(ops) | ast::Expr::Or(ops) => ops.iter().any(|o| has_recursion(o, fn_name)),
        ast::Expr::If(branches) => branches.iter().any(|(cond, body)| {
            cond.as_ref().is_some_and(|c| has_recursion(c, fn_name)) || has_recursion(body, fn_name)
        }),
        ast::Expr::Try(t, c) => has_recursion(t, fn_name) || has_recursion(c, fn_name),
        ast::Expr::SelectorCall(_, args) => args.iter().any(|a| has_recursion(a, fn_name)),
        ast::Expr::Paren(inner) => has_recursion(inner, fn_name),
        _ => false,
    }
}

/// Returns `true` if `node` contains any `Ident` reference that is not in `params`,
/// OR if any `Call` node uses a parameter name as its callee (those cannot be substituted
/// at the AST level because the callee position is an `IdentWithToken`, not an `Expr::Ident`).
///
/// Conservative: complex sub-expressions (blocks, lambdas, loops, let/var) cause
/// the function to return `true` immediately so that inlining is skipped.
fn has_free_vars(node: &Shared<ast::Node>, params: &[Ident]) -> bool {
    match &*node.expr {
        ast::Expr::Ident(ident) => !params.contains(&ident.name),
        ast::Expr::Literal(_) | ast::Expr::Self_ | ast::Expr::Selector(_) | ast::Expr::SelectorChain(_) => false,
        ast::Expr::Call(callee, args) => {
            // A parameter used as a callee cannot be inlined (callee is IdentWithToken, not Expr).
            params.contains(&callee.name) || args.iter().any(|a| has_free_vars(a, params))
        }
        ast::Expr::SelectorCall(_, args) => args.iter().any(|a| has_free_vars(a, params)),
        ast::Expr::And(ops) | ast::Expr::Or(ops) => ops.iter().any(|o| has_free_vars(o, params)),
        ast::Expr::If(branches) => branches
            .iter()
            .any(|(cond, body)| cond.as_ref().is_some_and(|c| has_free_vars(c, params)) || has_free_vars(body, params)),
        ast::Expr::Try(t, c) => has_free_vars(t, params) || has_free_vars(c, params),
        ast::Expr::Paren(inner) => has_free_vars(inner, params),
        _ => true,
    }
}

/// Substitute parameter references in `body` with the supplied arguments.
///
/// `Ident(param_name)` → corresponding `arg` node.
/// All other expression types are cloned unchanged.
fn substitute_params(
    node: Shared<ast::Node>,
    params: &[Ident],
    args: &Args,
    call_token_id: TokenId,
) -> Shared<ast::Node> {
    let token_id = call_token_id;
    match &*node.expr {
        ast::Expr::Ident(ident) => {
            if let Some(pos) = params.iter().position(|p| *p == ident.name) {
                return Shared::clone(&args[pos]);
            }
            node
        }
        ast::Expr::Call(ident, call_args) => {
            let subst: Args = call_args
                .iter()
                .map(|a| substitute_params(Shared::clone(a), params, args, call_token_id))
                .collect();
            Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::Call(ident.clone(), subst)),
            })
        }
        ast::Expr::SelectorCall(sel, call_args) => {
            let subst: Args = call_args
                .iter()
                .map(|a| substitute_params(Shared::clone(a), params, args, call_token_id))
                .collect();
            Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::SelectorCall(sel.clone(), subst)),
            })
        }
        ast::Expr::And(ops) => Shared::new(ast::Node {
            token_id,
            expr: Shared::new(ast::Expr::And(
                ops.iter()
                    .map(|o| substitute_params(Shared::clone(o), params, args, call_token_id))
                    .collect(),
            )),
        }),
        ast::Expr::Or(ops) => Shared::new(ast::Node {
            token_id,
            expr: Shared::new(ast::Expr::Or(
                ops.iter()
                    .map(|o| substitute_params(Shared::clone(o), params, args, call_token_id))
                    .collect(),
            )),
        }),
        ast::Expr::If(branches) => {
            let branches: ast::Branches = branches
                .iter()
                .map(|(cond, body)| {
                    (
                        cond.as_ref()
                            .map(|c| substitute_params(Shared::clone(c), params, args, call_token_id)),
                        substitute_params(Shared::clone(body), params, args, call_token_id),
                    )
                })
                .collect();
            Shared::new(ast::Node {
                token_id,
                expr: Shared::new(ast::Expr::If(branches)),
            })
        }
        ast::Expr::Try(t, c) => Shared::new(ast::Node {
            token_id,
            expr: Shared::new(ast::Expr::Try(
                substitute_params(Shared::clone(t), params, args, call_token_id),
                substitute_params(Shared::clone(c), params, args, call_token_id),
            )),
        }),
        ast::Expr::Paren(inner) => substitute_params(Shared::clone(inner), params, args, call_token_id),
        _ => node,
    }
}

fn literal_of(node: &Shared<ast::Node>) -> Option<Literal> {
    match &*node.expr {
        ast::Expr::Literal(lit) => Some(lit.clone()),
        _ => None,
    }
}

fn literal_eq(a: Literal, b: Literal) -> bool {
    match (a, b) {
        (Literal::Number(x), Literal::Number(y)) => x == y,
        (Literal::Bool(x), Literal::Bool(y)) => x == y,
        (Literal::String(x), Literal::String(y)) => x == y,
        (Literal::Symbol(x), Literal::Symbol(y)) => x == y,
        (Literal::Bytes(x), Literal::Bytes(y)) => x == y,
        (Literal::None, Literal::None) => true,
        _ => false,
    }
}

/// Scan `program` and rewrite self-tail-recursive `def` functions to use a loop.
fn apply_tco_transforms(program: Program) -> Program {
    program
        .into_iter()
        .map(|node| {
            let ast::Expr::Def(ident, params, body) = &*node.expr else {
                return node;
            };
            let param_names: Vec<Ident> = params.iter().map(|p| p.ident.name).collect();
            match try_tco_transform(ident.name, &param_names, body, node.token_id) {
                Some(new_body) => Shared::new(ast::Node {
                    token_id: node.token_id,
                    expr: Shared::new(ast::Expr::Def(ident.clone(), params.clone(), new_body)),
                }),
                None => node,
            }
        })
        .collect()
}

/// Returns `Some(new_body)` if `body` matches the TCO pattern:
/// - Single `If` node whose branches are either non-recursive base cases or direct self-calls.
/// - At least one base case and at least one recursive call.
fn try_tco_transform(fn_name: Ident, param_names: &[Ident], body: &Program, token_id: TokenId) -> Option<Program> {
    if body.len() != 1 {
        return None;
    }
    let ast::Expr::If(branches) = &*body[0].expr else {
        return None;
    };

    let mut has_recursive = false;
    let mut has_base = false;

    for (_, branch_body) in branches {
        if is_direct_self_call(branch_body, fn_name) {
            has_recursive = true;
        } else if !contains_self_call(branch_body, fn_name) {
            has_base = true;
        } else {
            return None;
        }
    }

    if !has_recursive || !has_base {
        return None;
    }

    Some(build_tco_loop(fn_name, param_names, branches, token_id))
}

/// Returns `true` if `node` is exactly `Call(fn_name, args)`.
fn is_direct_self_call(node: &Shared<ast::Node>, fn_name: Ident) -> bool {
    matches!(&*node.expr, ast::Expr::Call(ident, _) if ident.name == fn_name)
}

/// Returns `true` if `node` contains any call to `fn_name` at any depth.
fn contains_self_call(node: &Shared<ast::Node>, fn_name: Ident) -> bool {
    match &*node.expr {
        ast::Expr::Call(ident, args) => ident.name == fn_name || args.iter().any(|a| contains_self_call(a, fn_name)),
        ast::Expr::Ident(ident) => ident.name == fn_name,
        ast::Expr::And(ops) | ast::Expr::Or(ops) => ops.iter().any(|o| contains_self_call(o, fn_name)),
        ast::Expr::If(branches) => branches.iter().any(|(cond, body)| {
            cond.as_ref().is_some_and(|c| contains_self_call(c, fn_name)) || contains_self_call(body, fn_name)
        }),
        ast::Expr::Try(t, c) => contains_self_call(t, fn_name) || contains_self_call(c, fn_name),
        ast::Expr::SelectorCall(_, args) => args.iter().any(|a| contains_self_call(a, fn_name)),
        ast::Expr::Paren(inner) | ast::Expr::Break(Some(inner)) | ast::Expr::Unquote(inner) => {
            contains_self_call(inner, fn_name)
        }
        ast::Expr::Block(prog) => prog.iter().any(|n| contains_self_call(n, fn_name)),
        _ => false,
    }
}

/// Build the loop-based body that replaces a tail-recursive function.
///
/// For `def f(a, b): if (cond): base else: f(new_a, new_b);` generates:
/// ```text
/// var __tco_a = a;
/// var __tco_b = b;
/// loop {
///   let a = __tco_a;
///   let b = __tco_b;
///   if (cond): break base
///   else: { __tco_a = new_a; __tco_b = new_b; continue }
/// }
/// ```
fn build_tco_loop(fn_name: Ident, param_names: &[Ident], branches: &Branches, token_id: TokenId) -> Program {
    let syn = |expr: ast::Expr| -> Shared<ast::Node> {
        Shared::new(ast::Node {
            token_id,
            expr: Shared::new(expr),
        })
    };

    let tco_ident = |p: Ident| IdentWithToken::new(&format!("__tco_{}", p.as_str()));

    // var __tco_p = p;
    let var_decls: Program = param_names
        .iter()
        .map(|p| {
            syn(ast::Expr::Var(
                Pattern::Ident(tco_ident(*p)),
                syn(ast::Expr::Ident(IdentWithToken::new(&p.as_str()))),
            ))
        })
        .collect();

    // let p = __tco_p;  (re-bind at the top of each loop iteration)
    let let_rebinds: Program = param_names
        .iter()
        .map(|p| {
            syn(ast::Expr::Let(
                Pattern::Ident(IdentWithToken::new(&p.as_str())),
                syn(ast::Expr::Ident(tco_ident(*p))),
            ))
        })
        .collect();

    // Transform each If branch
    let new_branches: Branches = branches
        .iter()
        .map(|(cond, body)| {
            let new_body = if is_direct_self_call(body, fn_name) {
                let ast::Expr::Call(_, rec_args) = &*body.expr else {
                    unreachable!()
                };
                // __tco_p = new_p; continue
                let mut block: Program = param_names
                    .iter()
                    .zip(rec_args.iter())
                    .map(|(p, new_val)| syn(ast::Expr::Assign(tco_ident(*p), Shared::clone(new_val))))
                    .collect();
                block.push(syn(ast::Expr::Continue));
                syn(ast::Expr::Block(block))
            } else {
                syn(ast::Expr::Break(Some(Shared::clone(body))))
            };
            (cond.clone(), new_body)
        })
        .collect();

    let mut loop_body = let_rebinds;
    loop_body.push(syn(ast::Expr::If(new_branches)));

    let mut result = var_decls;
    result.push(syn(ast::Expr::Loop(loop_body)));
    result
}

/// Returns `true` if `n` is exactly the integer 1.
#[inline]
fn is_one(n: &crate::number::Number) -> bool {
    (n.value() - 1.0).abs() < f64::EPSILON
}

/// Collect the names of every function directly called in `program` (recursively).
fn collect_called_fns(program: &Program) -> FxHashSet<Ident> {
    let mut set = FxHashSet::default();
    for node in program {
        collect_called_fns_node(node, &mut set);
    }
    set
}

fn collect_called_fns_node(node: &Shared<ast::Node>, set: &mut FxHashSet<Ident>) {
    match &*node.expr {
        ast::Expr::Call(ident, args) => {
            set.insert(ident.name);
            for a in args {
                collect_called_fns_node(a, set);
            }
        }
        // An ident may be a first-class function value (e.g. passed to `map`, `filter`);
        // record it so we don't accidentally eliminate its Def.
        ast::Expr::Ident(ident) => {
            set.insert(ident.name);
        }
        ast::Expr::Def(_, _, body) | ast::Expr::Block(body) | ast::Expr::Loop(body) | ast::Expr::Module(_, body) => {
            for n in body {
                collect_called_fns_node(n, set);
            }
        }
        ast::Expr::Fn(_, body) => {
            for n in body {
                collect_called_fns_node(n, set);
            }
        }
        ast::Expr::If(branches) => {
            for (cond, body) in branches {
                if let Some(c) = cond {
                    collect_called_fns_node(c, set);
                }
                collect_called_fns_node(body, set);
            }
        }
        ast::Expr::And(ops) | ast::Expr::Or(ops) => {
            for o in ops {
                collect_called_fns_node(o, set);
            }
        }
        ast::Expr::Try(t, c) => {
            collect_called_fns_node(t, set);
            collect_called_fns_node(c, set);
        }
        ast::Expr::SelectorCall(_, args) => {
            for a in args {
                collect_called_fns_node(a, set);
            }
        }
        ast::Expr::CallDynamic(callee, args) => {
            collect_called_fns_node(callee, set);
            for a in args {
                collect_called_fns_node(a, set);
            }
        }
        ast::Expr::Let(_, rhs) | ast::Expr::Var(_, rhs) | ast::Expr::Assign(_, rhs) | ast::Expr::As(_, rhs) => {
            collect_called_fns_node(rhs, set);
        }
        ast::Expr::While(cond, body) | ast::Expr::Foreach(_, cond, body) => {
            collect_called_fns_node(cond, set);
            for n in body {
                collect_called_fns_node(n, set);
            }
        }
        ast::Expr::Match(val, arms) => {
            collect_called_fns_node(val, set);
            for arm in arms {
                if let Some(g) = &arm.guard {
                    collect_called_fns_node(g, set);
                }
                collect_called_fns_node(&arm.body, set);
            }
        }
        ast::Expr::Paren(inner) | ast::Expr::Break(Some(inner)) | ast::Expr::Unquote(inner) => {
            collect_called_fns_node(inner, set);
        }
        ast::Expr::InterpolatedString(segs) => {
            for seg in segs {
                if let StringSegment::Expr(n) = seg {
                    collect_called_fns_node(n, set);
                }
            }
        }
        _ => {}
    }
}

/// Remove top-level `Def` nodes that were inlined everywhere they were called.
///
/// Only removes `Def`s that were candidates for inlining (present in `inlinable`) and
/// are no longer referenced by any `Call` in the program. Non-inlinable functions (recursive,
/// variadic, TCO-transformed) are always preserved because they may be called at runtime.
fn eliminate_dead_defs(program: Program, inlinable: &FxHashMap<Ident, InlinableFn>) -> Program {
    if inlinable.is_empty() {
        return program;
    }
    let used = collect_called_fns(&program);
    program
        .into_iter()
        .filter(|node| match &*node.expr {
            ast::Expr::Def(ident, _, _) => !inlinable.contains_key(&ident.name) || used.contains(&ident.name),
            _ => true,
        })
        .collect()
}

fn literal_is_truthy(lit: &Literal) -> bool {
    match lit {
        Literal::Bool(b) => *b,
        Literal::Number(n) => !n.is_zero(),
        Literal::String(s) => !s.is_empty(),
        Literal::Symbol(_) => true,
        Literal::Bytes(b) => !b.is_empty(),
        Literal::None => false,
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        DefaultEngine,
        ast::node::{Expr, Literal},
        optimizer::OptimizationLevel,
    };
    use rstest::rstest;

    /// Compile `query` at the given `level` and return the resulting AST.
    fn ast_with(query: &str, level: OptimizationLevel) -> crate::ast::Program {
        let mut engine = DefaultEngine::default();
        engine.set_optimization_level(level);
        engine.compile(query).unwrap().program().clone()
    }

    fn ast_none(query: &str) -> crate::ast::Program {
        ast_with(query, OptimizationLevel::None)
    }

    fn ast_basic(query: &str) -> crate::ast::Program {
        ast_with(query, OptimizationLevel::Basic)
    }

    fn ast_full(query: &str) -> crate::ast::Program {
        ast_with(query, OptimizationLevel::Full)
    }

    fn assert_literal(node: &crate::Shared<crate::AstNode>, expected: &str, ctx: &str) {
        match &*node.expr {
            Expr::Literal(lit) => assert_eq!(lit.to_string(), expected, "{ctx}"),
            other => panic!("{ctx}: expected Literal({expected:?}), got {other:?}"),
        }
    }

    #[test]
    fn none_arithmetic_stays_as_call() {
        let prog = ast_none("1 + 2");
        assert_eq!(prog.len(), 1);
        assert!(
            matches!(&*prog[0].expr, Expr::Call(..)),
            "None: expected Call, got {:?}",
            prog[0].expr
        );
    }

    #[test]
    fn none_consecutive_selectors_stay_separate() {
        let prog = ast_none(".h1 | .text");
        assert_eq!(prog.len(), 2, "None must not merge selectors");
        assert!(matches!(&*prog[0].expr, Expr::Selector(_)));
        assert!(matches!(&*prog[1].expr, Expr::Selector(_)));
    }

    #[test]
    fn none_if_with_literal_cond_stays_as_if() {
        let prog = ast_none("if (true): 1 else: 2");
        assert_eq!(prog.len(), 1);
        assert!(
            matches!(&*prog[0].expr, Expr::If(_)),
            "None: expected If, got {:?}",
            prog[0].expr
        );
    }

    #[test]
    fn none_and_stays_as_and() {
        let prog = ast_none("false && .");
        assert_eq!(prog.len(), 1);
        assert!(
            matches!(&*prog[0].expr, Expr::And(_)),
            "None: expected And, got {:?}",
            prog[0].expr
        );
    }

    #[test]
    fn none_interpolated_string_stays_unfolded() {
        let prog = ast_none("s\"hello world\"");
        assert_eq!(prog.len(), 1);
        assert!(
            matches!(&*prog[0].expr, Expr::InterpolatedString(_)),
            "None: expected InterpolatedString, got {:?}",
            prog[0].expr
        );
    }

    #[test]
    fn none_def_body_stays_as_if_no_tco() {
        let prog = ast_none("def countdown(n): if (n == 0): \"done\" else: countdown(n - 1);");
        assert_eq!(prog.len(), 1);
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            !body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "None: must not apply TCO; Loop found in body"
        );
        assert!(
            body.iter().any(|n| matches!(&*n.expr, Expr::If(_))),
            "None: original If must remain in body"
        );
    }

    #[rstest]
    #[case("1 + 2", "3")]
    #[case("10 - 3", "7")]
    #[case("3 * 4", "12")]
    #[case("10 / 2", "5")]
    #[case("10 % 3", "1")]
    #[case("\"hello\" + \" world\"", "hello world")]
    #[case("negate(5)", "-5")]
    #[case("not(false)", "true")]
    #[case("not(true)", "false")]
    fn fold_arithmetic_to_literal(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: expected single literal node");
            assert_literal(&prog[0], expected, &format!("{level:?}"));
        }
    }

    #[rstest]
    #[case("1 == 1", "true")]
    #[case("1 == 2", "false")]
    #[case("1 != 2", "true")]
    #[case("1 != 1", "false")]
    #[case("1 < 2", "true")]
    #[case("2 < 1", "false")]
    #[case("2 <= 2", "true")]
    #[case("3 > 2", "true")]
    #[case("2 > 3", "false")]
    #[case("2 >= 2", "true")]
    fn fold_comparisons_to_literal(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: expected single literal node");
            assert_literal(&prog[0], expected, &format!("{level:?}"));
        }
    }

    #[test]
    fn fold_nested_arithmetic_to_literal() {
        // (1 + 2) * (3 + 4) — both sub-expressions fold first, then the outer mul folds.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("(1 + 2) * (3 + 4)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "21", &format!("{level:?}"));
        }
    }

    #[test]
    fn fold_double_negation_to_literal() {
        // not(not(true)) → true
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("not(not(true))", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "true", &format!("{level:?}"));
        }
    }

    #[test]
    fn div_by_zero_not_folded() {
        // Division by zero must stay as Call — the evaluator handles the error.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("1 / 0", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: div-by-zero must stay as Call, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn dynamic_arg_prevents_folding() {
        // add(., 1): left operand is the pipeline value — not a literal, cannot fold.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("add(., 1)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: dynamic arg must prevent folding, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn if_true_collapses_to_then_body() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (true): 1 else: 2", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "1", &format!("{level:?}: if(true)"));
        }
    }

    #[test]
    fn if_false_collapses_to_else_body() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (false): 1 else: 2", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "2", &format!("{level:?}: if(false)+else"));
        }
    }

    #[test]
    fn if_false_no_else_collapses_to_literal_none() {
        // All branches eliminated → optimizer emits Literal::None.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (false): 1", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::None)),
                "{level:?}: expected Literal(None), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn if_foldable_condition_also_eliminated() {
        // Condition `1 == 1` folds to `true`, then branch is eliminated.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (1 == 1): \"yes\" else: \"no\"", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "yes", &format!("{level:?}"));
        }
    }

    #[test]
    fn if_dynamic_condition_stays_as_if() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (.): 1 else: 2", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::If(_)),
                "{level:?}: dynamic condition must not eliminate branch, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn elif_first_true_branch_wins() {
        // `if (false): 1 elif (true): 2 elif (true): 3 else: 4` → Literal(2)
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (false): 1 elif (true): 2 elif (true): 3 else: 4", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "2", &format!("{level:?}"));
        }
    }

    #[test]
    fn elif_all_false_no_else_collapses_to_literal_none() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (false): 1 elif (false): 2 elif (false): 3", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::None)),
                "{level:?}: expected Literal(None), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn nested_if_both_levels_eliminated() {
        // `if (true): if (false): 1 else: 2 else: 3` → outer true → inner, inner false → 2
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (true): if (false): 1 else: 2 else: 3", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "2", &format!("{level:?}"));
        }
    }

    #[test]
    fn and_falsy_literal_short_circuits_to_false() {
        // `false && .` — falsy operand → entire And becomes Literal(false).
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("false && .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::Bool(false))),
                "{level:?}: expected Literal(false), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn and_truthy_literal_dropped_dynamic_preserved() {
        // `true && .` — truthy literal is dropped; remaining dynamic operand wrapped in And.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("true && .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::And(_)),
                "{level:?}: expected And([.]), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn and_all_truthy_collapses_to_literal_true() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("true && true && true", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::Bool(true))),
                "{level:?}: expected Literal(true), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn or_truthy_literal_short_circuits() {
        // `true || .` — truthy operand → entire Or becomes Literal(true).
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("true || .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::Bool(true))),
                "{level:?}: expected Literal(true), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn or_falsy_literal_dropped_dynamic_preserved() {
        // `false || .` — falsy literal is dropped; remaining dynamic operand wrapped in Or.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("false || .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Or(_)),
                "{level:?}: expected Or([.]), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn or_all_falsy_collapses_to_literal_false() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("false || false || false", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::Bool(false))),
                "{level:?}: expected Literal(false), got {:?}",
                prog[0].expr
            );
        }
    }

    #[rstest]
    #[case(".h1 | .text", 2usize)]
    #[case(".h1 | .text | .code", 3usize)]
    fn consecutive_selectors_merged_into_chain(#[case] query: &str, #[case] expected_len: usize) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: expected single SelectorChain node");
            assert!(
                matches!(&*prog[0].expr, Expr::SelectorChain(c) if c.len() == expected_len),
                "{level:?}: expected SelectorChain(len={expected_len}), got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn single_selector_stays_as_selector_not_chain() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(".h1", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Selector(_)),
                "{level:?}: single selector must NOT become SelectorChain"
            );
        }
    }

    #[rstest]
    #[case(".h1 | to_string | .text")]
    #[case(".h1 | len() | .text")]
    fn call_between_selectors_prevents_chain_merge(#[case] query: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert!(prog.len() > 1, "{level:?}: call between selectors must break the chain");
            assert!(
                !matches!(&*prog[0].expr, Expr::SelectorChain(_)),
                "{level:?}: must not merge selectors across a call"
            );
        }
    }

    #[test]
    fn none_level_does_not_merge_selectors() {
        let prog = ast_none(".h1 | .text");
        assert_eq!(prog.len(), 2, "None must not merge consecutive selectors");
        assert!(matches!(&*prog[0].expr, Expr::Selector(_)));
        assert!(matches!(&*prog[1].expr, Expr::Selector(_)));
    }

    #[test]
    fn selector_chain_inside_def_body_merged() {
        // Full inlines single-node def bodies and then eliminates the unused Def.
        // `.h1 | .text` is merged into SelectorChain during inlining, so the final program
        // has one top-level SelectorChain (the inlined call site) and no Def.
        let prog = ast_full("def extract: .h1 | .text; | extract()");
        assert!(
            prog.iter().any(|n| matches!(&*n.expr, Expr::SelectorChain(_))),
            "Full: inlined extract() must produce a top-level SelectorChain"
        );
        assert!(
            !prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: fully-inlined Def must be eliminated"
        );
    }

    #[rstest]
    #[case("s\"hello world\"", "hello world")]
    #[case("s\"static text only\"", "static text only")]
    fn all_text_interpolated_string_folded_to_literal(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(_)),
                "{level:?}: all-text interpolated string must fold to Literal"
            );
            assert_literal(&prog[0], expected, &format!("{level:?}"));
        }
    }

    #[test]
    fn interpolated_string_with_dynamic_expr_not_folded() {
        // A dynamic segment (`${self}`) prevents folding.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("s\"${self} end\"", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::InterpolatedString(_)),
                "{level:?}: dynamic segment must prevent folding to Literal"
            );
        }
    }

    #[test]
    fn none_level_does_not_fold_interpolated_string() {
        // Even a fully-static string must stay as InterpolatedString under None.
        let prog = ast_none("s\"hello world\"");
        assert_eq!(prog.len(), 1);
        assert!(
            matches!(&*prog[0].expr, Expr::InterpolatedString(_)),
            "None must not fold interpolated strings"
        );
    }

    #[test]
    fn let_literal_propagated_and_folded_in_full() {
        // Full: x is bound to 5, substituted into `x + 1`, folded to 6.
        let prog = ast_full("let x = 5 | x + 1");
        assert_eq!(prog.len(), 2);
        assert_literal(&prog[1], "6", "Full: x+1 after propagation");
    }

    #[test]
    fn let_literal_not_propagated_in_basic() {
        // Basic does not propagate — `x + 1` stays as Call with Ident.
        let prog = ast_basic("let x = 5 | x + 1");
        assert_eq!(prog.len(), 2);
        assert!(
            matches!(&*prog[1].expr, Expr::Call(..)),
            "Basic must not propagate let-literals; expected Call, got {:?}",
            prog[1].expr
        );
    }

    #[test]
    fn let_rebind_propagates_latest_value() {
        // Second binding of x shadows the first; `x + 0` folds to 2.
        let prog = ast_full("let x = 1 | let x = 2 | x + 0");
        assert_eq!(prog.len(), 3);
        assert_literal(&prog[2], "2", "Full: second binding must shadow first");
    }

    #[test]
    fn let_multiple_bindings_all_propagated() {
        // Three bindings, all propagated and folded into a single literal.
        let prog = ast_full("let a = 2 | let b = 3 | let c = 4 | a + b + c");
        assert_eq!(prog.len(), 4);
        assert_literal(&prog[3], "9", "Full: a+b+c after propagation");
    }

    #[test]
    fn let_non_literal_rhs_not_propagated() {
        // `let x = add(1, .)` — RHS is not a literal (dynamic arg) → x is not registered.
        // Full folds `x + 0` to `x` via algebraic identity, but `x` stays as Ident (not a
        // literal), proving the let binding was not propagated to a constant.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("let x = add(1, .) | x + 0", level);
            assert_eq!(prog.len(), 2, "{level:?}");
            assert!(
                !matches!(&*prog[1].expr, Expr::Literal(_)),
                "{level:?}: non-literal let must not propagate to a literal, got {:?}",
                prog[1].expr
            );
        }
    }

    #[test]
    fn simple_function_inlined_and_folded_in_full() {
        // Full: double(4) → inlined to 4 * 2 → folded to Literal(8).
        let prog = ast_full("def double(x): x * 2; | double(4)");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(_)),
            "Full: inlined+folded call must be Literal, got {:?}",
            last.expr
        );
        assert_literal(last, "8", "Full: double(4)");
    }

    #[test]
    fn function_call_stays_as_call_in_basic() {
        // Basic does not inline — the call node is preserved.
        let prog = ast_basic("def double(x): x * 2; | double(4)");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Call(..)),
            "Basic must not inline; expected Call, got {:?}",
            last.expr
        );
    }

    #[test]
    fn zero_param_constant_alias_inlined_in_full() {
        let prog = ast_full("def pi: 3; | pi()");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(_)),
            "Full: 0-param constant alias must inline to Literal, got {:?}",
            last.expr
        );
        assert_literal(last, "3", "Full: pi()");
    }

    #[test]
    fn recursive_function_not_inlined() {
        // Recursive functions must never be inlined (infinite unrolling).
        let prog = ast_full("def fact(n): if (n == 0): 1 else: n * fact(n - 1); | fact(5)");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Call(..)),
            "Full: recursive function must not be inlined; expected Call, got {:?}",
            last.expr
        );
    }

    #[test]
    fn function_with_free_variable_not_inlined() {
        // `add_k` references `k` which is not a parameter → not inlineable.
        let prog = ast_full("let k = 10 | def add_k(x): x + k; | add_k(5)");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Call(..)),
            "Full: function with free var must not be inlined; expected Call, got {:?}",
            last.expr
        );
    }

    #[test]
    fn chained_inlining_collapses_to_literal() {
        // Both add1 and mul2 are inlineable; mul2(add1(3)) → (3+1)*2 → 8.
        let prog = ast_full("def add1(x): x + 1; | def mul2(x): x * 2; | mul2(add1(3))");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(_)),
            "Full: chained inline+fold must collapse to Literal, got {:?}",
            last.expr
        );
        assert_literal(last, "8", "Full: mul2(add1(3))");
    }

    #[test]
    fn tco_tail_recursive_def_gets_loop_in_full() {
        let prog = ast_full("def countdown(n): if (n == 0): \"done\" else: countdown(n - 1);");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "Full: TCO-transformed Def must contain a Loop node"
        );
        // The original top-level If must be replaced — not left alongside the Loop.
        assert!(
            !body.iter().any(|n| matches!(&*n.expr, Expr::If(_))),
            "Full: original If must be replaced by Loop after TCO"
        );
    }

    #[test]
    fn tco_not_applied_in_basic() {
        let prog = ast_basic("def countdown(n): if (n == 0): \"done\" else: countdown(n - 1);");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            !body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "Basic must not apply TCO; Loop found unexpectedly"
        );
    }

    #[test]
    fn tco_not_applied_in_none() {
        let prog = ast_none("def countdown(n): if (n == 0): \"done\" else: countdown(n - 1);");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            !body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "None must not apply TCO"
        );
    }

    #[test]
    fn tco_not_applied_to_non_tail_call() {
        // `n * fact(n-1)` is a binary op wrapping the recursive call — NOT a tail call.
        let prog = ast_full("def fact(n): if (n == 0): 1 else: n * fact(n - 1);");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            !body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "Full: non-tail-recursive function must not be TCO-transformed"
        );
    }

    #[test]
    fn tco_multi_param_def_gets_loop() {
        let prog = ast_full("def loop2(a, b): if (a == 0): b else: loop2(a - 1, b + 1);");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            body.iter().any(|n| matches!(&*n.expr, Expr::Loop(_))),
            "Full: multi-param tail-recursive Def must contain Loop"
        );
    }

    #[test]
    fn inline_then_constant_fold() {
        // double(3 + 4): argument folds to 7, then inlined body 7 * 2 folds to 14.
        let prog = ast_full("def double(x): x * 2; | double(3 + 4)");
        let last = prog.last().unwrap();
        assert_literal(last, "14", "Full: double(3+4)");
    }

    #[test]
    fn inline_reveals_dead_branch() {
        // always_false(0) inlines to `0 == 999`, folds to false, if-branch eliminated.
        let prog = ast_full("def always_false(x): x == 999; | if (always_false(0)): \"bad\" else: \"good\"");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(_)),
            "Full: inline+dead-branch must collapse to Literal, got {:?}",
            last.expr
        );
        assert_literal(last, "good", "Full: always_false(0)");
    }

    #[test]
    fn let_propagation_enables_inline_and_fold() {
        // n=9 propagated, inc(9) inlined to 9+1, folded to 10.
        let prog = ast_full("def inc(x): x + 1; | let n = 9 | inc(n)");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(_)),
            "Full: propagation+inline+fold must collapse to Literal, got {:?}",
            last.expr
        );
        assert_literal(last, "10", "Full: inc(n) where n=9");
    }

    #[test]
    fn fold_then_dead_branch_elimination() {
        // `if (1 + 2 == 3): "yes" else: "no"` — fold condition first, then eliminate branch.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("if (1 + 2 == 3): \"yes\" else: \"no\"", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "yes", &format!("{level:?}"));
        }
    }

    #[test]
    fn let_propagation_into_and_or_operands() {
        // `let n = 0 | n == 0 && true` — n substituted, `0 == 0` folds to true,
        // then `true && true` collapses to Literal(true).
        let prog = ast_full("let n = 0 | n == 0 && true");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Literal(Literal::Bool(true))),
            "Full: propagation+and fold must collapse to Literal(true), got {:?}",
            last.expr
        );
    }

    #[rstest]
    #[case("floor(3.9)", "3")]
    #[case("ceil(3.1)", "4")]
    #[case("round(3.5)", "4")]
    #[case("abs(-7)", "7")]
    #[case("trunc(3.9)", "3")]
    fn numeric_unary_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("len(\"hello\")", "5")]
    #[case("len(\"\")", "0")]
    fn len_string_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("to_string(42)", "42")]
    #[case("to_string(3.5)", "3.5")]
    #[case("to_string(true)", "true")]
    #[case("to_string(false)", "false")]
    fn to_string_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("to_number(\"42\")", "42")]
    #[case("to_number(\"3.14\")", "3.14")]
    fn to_number_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[test]
    fn to_number_invalid_string_not_folded() {
        // Runtime would return an error — optimizer must not fold.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("to_number(\"abc\")", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: unparseable to_number must stay as Call, got {:?}",
                prog[0].expr
            );
        }
    }

    #[rstest]
    #[case("lt(\"a\", \"b\")", "true")] // #[case(..)]  "a" < "b"
    #[case("gt(\"b\", \"a\")", "true")]
    #[case("lte(\"a\", \"a\")", "true")]
    #[case("gte(\"b\", \"a\")", "true")]
    #[case("lt(\"b\", \"a\")", "false")]
    fn string_comparison_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[test]
    fn algebraic_identity_add_zero() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(". + 0", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: . + 0 must fold to Self_, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn algebraic_identity_mul_zero() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(". * 0", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "0", &format!("{level:?}: . * 0"));
        }
    }

    #[test]
    fn algebraic_identity_mul_one() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(". * 1", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: . * 1 must fold to Self_, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn algebraic_identity_div_one() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(". / 1", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: . / 1 must fold to Self_, got {:?}",
                prog[0].expr
            );
        }
    }

    #[rstest]
    #[case("trim(\"  hi  \")", "hi")]
    #[case("ltrim(\"  hi\")", "hi")]
    #[case("rtrim(\"hi  \")", "hi")]
    #[case("upcase(\"hello\")", "HELLO")]
    #[case("downcase(\"WORLD\")", "world")]
    fn string_transform_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("starts_with(\"hello\", \"he\")", "true")]
    #[case("starts_with(\"hello\", \"wo\")", "false")]
    #[case("ends_with(\"hello\", \"lo\")", "true")]
    #[case("ends_with(\"hello\", \"he\")", "false")]
    #[case("index(\"hello\", \"ll\")", "2")]
    #[case("index(\"hello\", \"xx\")", "-1")]
    #[case("rindex(\"hello\", \"l\")", "3")]
    fn string_search_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("replace(\"hello\", \"l\", \"r\")", "herro")]
    #[case("replace(\"aaa\", \"a\", \"b\")", "bbb")]
    fn replace_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[test]
    fn coalesce_none_folded() {
        // coalesce(None, .) → Self_ (rhs is dynamic; None is Literal::None)
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("coalesce(None, .)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: coalesce(None, .) must fold to Self_, got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn coalesce_non_none_lhs_folded() {
        // coalesce("hi", .) → "hi" (lhs is non-none, rhs is never evaluated)
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("coalesce(\"hi\", .)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "hi", &format!("{level:?}: coalesce(\"hi\", .)"));
        }
    }

    #[test]
    fn coalesce_both_literals_folded() {
        // coalesce(None, 42) → 42 (both are literals)
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("coalesce(None, 42)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert_literal(&prog[0], "42", &format!("{level:?}: coalesce(None, 42)"));
        }
    }

    #[test]
    fn user_def_shadows_builtin_uses_user_semantics() {
        // User's `upcase(x): x` is an identity — it gets inlined, producing "hello".
        // The builtin would produce "HELLO". Verifying we get "hello" proves the
        // user's definition was used (via inlining), not the builtin's constant fold.
        let prog = ast_full("def upcase(x): x; | upcase(\"hello\")");
        let last = prog.last().unwrap();
        assert_literal(
            last,
            "hello",
            "Full: user-shadowed upcase must produce identity, not builtin 'HELLO'",
        );
    }

    #[test]
    fn user_def_shadows_trim_uses_user_semantics() {
        // User's `trim(x): x` is an identity. Builtin would strip spaces → "hi".
        // After inlining, result should be "  hi  " (spaces preserved).
        let prog = ast_full("def trim(x): x; | trim(\"  hi  \")");
        let last = prog.last().unwrap();
        assert_literal(last, "  hi  ", "Full: user-shadowed trim must preserve spaces");
    }

    #[test]
    fn non_shadowed_builtin_still_folded() {
        // Having an unrelated user def must not block folding of other builtins.
        let prog = ast_full("def my_fn(x): x; | upcase(\"hello\")");
        let last = prog.last().unwrap();
        assert_literal(last, "HELLO", "Full: non-shadowed upcase must fold");
    }

    #[rstest]
    #[case("trim(\"  a  \")", "a")]
    #[case("ltrim(\"  a\")", "a")]
    #[case("rtrim(\"a  \")", "a")]
    #[case("trim(\"\")", "")]
    #[case("upcase(\"abc\")", "ABC")]
    #[case("downcase(\"XYZ\")", "xyz")]
    #[case("upcase(\"123\")", "123")]
    fn string_ops_fold(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[test]
    fn string_ops_with_dynamic_arg_not_folded() {
        for q in ["trim(.)", "upcase(.)"] {
            for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
                let prog = ast_with(q, level);
                assert_eq!(prog.len(), 1, "{level:?}: {q}");
                assert!(
                    matches!(&*prog[0].expr, Expr::Call(..)),
                    "{level:?}: {q} must remain Call"
                );
            }
        }
    }

    #[rstest]
    #[case("starts_with(\"hello\", \"he\")", "true")]
    #[case("starts_with(\"hello\", \"lo\")", "false")]
    #[case("ends_with(\"world\", \"ld\")", "true")]
    #[case("ends_with(\"world\", \"wo\")", "false")]
    #[case("index(\"abcabc\", \"bc\")", "1")]
    #[case("rindex(\"abcabc\", \"bc\")", "4")]
    #[case("index(\"abc\", \"x\")", "-1")]
    fn string_search_fold(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("replace(\"aabbcc\", \"b\", \"x\")", "aaxxcc")]
    #[case("replace(\"hello\", \"l\", \"\")", "heo")]
    #[case("replace(\"\", \"x\", \"y\")", "")]
    fn replace_fold(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("floor(3.7)", "3")]
    #[case("floor(-1.2)", "-2")]
    #[case("ceil(3.1)", "4")]
    #[case("ceil(-1.8)", "-1")]
    #[case("round(2.5)", "3")]
    #[case("round(2.4)", "2")]
    #[case("abs(-5)", "5")]
    #[case("abs(5)", "5")]
    #[case("trunc(3.9)", "3")]
    #[case("trunc(-3.9)", "-3")]
    fn numeric_math_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[test]
    fn numeric_math_dynamic_not_folded() {
        for q in ["floor(.)", "abs(.)"] {
            let prog = ast_basic(q);
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{q} with dynamic arg must stay Call"
            );
        }
    }

    #[rstest]
    #[case("len(\"\")", "0")]
    #[case("len(\"hello\")", "5")]
    #[case("len(\"こんにちは\")", "5")] // Unicode: 5 chars
    fn len_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("to_string(0)", "0")]
    #[case("to_string(\"hi\")", "hi")]
    #[case("to_string(true)", "true")]
    fn to_string_lit_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case("to_number(\"-1\")", "-1")]
    #[case("to_number(\"0.5\")", "0.5")]
    fn to_number_lit_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case(". + 0")]
    #[case("0 + .")]
    #[case(". - 0")]
    #[case(". * 1")]
    #[case("1 * .")]
    #[case(". / 1")]
    fn algebraic_identity_returns_self(#[case] query: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: {query} must fold to Self_"
            );
        }
    }

    #[rstest]
    #[case(". * 0")]
    #[case("0 * .")]
    fn algebraic_mul_zero_returns_literal_zero(#[case] query: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], "0", &format!("{level:?}: {query}"));
        }
    }

    #[rstest]
    #[case(". + \"\"")]
    #[case("\"\" + .")]
    fn algebraic_add_empty_string_returns_self(#[case] query: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: {query} must fold to Self_"
            );
        }
    }

    #[test]
    fn constant_fold_inside_block() {
        // Blocks are nested scopes; constant folding must still apply.
        let prog = ast_basic("(1 + 2)");
        assert_eq!(prog.len(), 1);
        assert_literal(&prog[0], "3", "Basic: (1+2) inside Paren must fold");
    }

    #[test]
    fn selector_chain_merged_inside_while_body() {
        // The selector chain inside a while condition (2 selectors) must merge.
        // while(.h1 | .text) is only 2 nodes in the condition, but the condition
        // itself is a single Call node; so we check a def body instead.
        let prog = ast_basic("def f: .h1 | .text;");
        let Expr::Def(_, _, body) = &*prog[0].expr else {
            panic!("expected Def");
        };
        assert!(
            body.iter().any(|n| matches!(&*n.expr, Expr::SelectorChain(_))),
            "Basic: SelectorChain must be merged inside Def body"
        );
    }

    #[test]
    fn nested_let_literal_not_propagated_across_scope() {
        // A let binding defined at the top level must not propagate into a nested
        // def body — they are separate scopes.
        let prog = ast_full("let x = 99 | def f: x;");
        let Expr::Def(_, _, body) = &*prog.iter().find(|n| matches!(&*n.expr, Expr::Def(..))).unwrap().expr else {
            panic!("expected Def");
        };
        assert!(
            matches!(&*body[0].expr, Expr::Ident(_)),
            "Full: top-level let must not propagate into def body, got {:?}",
            body[0].expr
        );
    }

    #[test]
    fn inlined_def_is_eliminated() {
        // After inlining, the Def is no longer called → eliminated.
        let prog = ast_full("def double(x): x * 2; | double(5)");
        assert!(
            !prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: fully-inlined Def must be eliminated from the program"
        );
        let last = prog.last().unwrap();
        assert_literal(last, "10", "Full: double(5) must fold to 10");
    }

    #[test]
    fn non_inlinable_def_preserved() {
        // A recursive Def is not inlinable → must be kept.
        let prog = ast_full("def count(n): if (n == 0): 0 else: count(n - 1);");
        assert!(
            prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: non-inlinable Def must be preserved"
        );
    }

    #[test]
    fn def_passed_as_value_not_eliminated() {
        // When a Def is passed as a first-class function value, it must not be eliminated.
        let prog = ast_full("def is_pos(x): gt(x, 0); | filter(array(1, -1, 2), is_pos)");
        assert!(
            prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: Def passed as first-class value must be preserved"
        );
    }

    #[test]
    fn tco_only_in_full() {
        let query = "def sum(n): if (n == 0): 0 else: sum(n - 1);";
        let none_prog = ast_none(query);
        let basic_prog = ast_basic(query);
        let full_prog = ast_full(query);

        let has_loop = |prog: &crate::ast::Program| {
            prog.iter().any(|n| {
                if let Expr::Def(_, _, body) = &*n.expr {
                    body.iter().any(|b| matches!(&*b.expr, Expr::Loop(_)))
                } else {
                    false
                }
            })
        };
        assert!(!has_loop(&none_prog), "None: no TCO");
        assert!(!has_loop(&basic_prog), "Basic: no TCO");
        assert!(has_loop(&full_prog), "Full: TCO must apply");
    }

    #[test]
    fn none_level_is_identity() {
        // At None, the program must be returned byte-for-byte unchanged.
        let queries = ["1 + 2", "if (true): 1 else: 2", "false && .", "def f(x): x + 1; | f(5)"];
        for q in queries {
            let none = ast_none(q);
            let basic = ast_basic(q);
            assert!(!none.is_empty(), "None: {q} must produce nodes");
            assert!(none.len() >= basic.len(), "None: {q}");
        }
    }

    #[test]
    fn chained_string_ops_fold() {
        // upcase(trim("  hello  ")) → upcase("hello") → "HELLO"
        let prog = ast_full("upcase(trim(\"  hello  \"))");
        assert_eq!(prog.len(), 1);
        assert_literal(&prog[0], "HELLO", "Full: chained upcase(trim(...)) must fold");
    }

    #[test]
    fn nested_arithmetic_folds() {
        // floor(abs(-3.7) + 1) → floor(3.7 + 1) → floor(4.7) → 4
        let prog = ast_full("floor(abs(-3.7) + 1)");
        assert_eq!(prog.len(), 1);
        assert_literal(&prog[0], "4", "Full: nested floor(abs+add) must fold");
    }

    #[test]
    fn let_chain_propagation() {
        // let a = 1 | let b = 2 | let c = a + b → 3
        let prog = ast_full("let a = 1 | let b = 2 | a + b");
        let last = prog.last().unwrap();
        assert_literal(last, "3", "Full: chained let propagation must fold to 3");
    }

    #[test]
    fn let_and_string_propagation() {
        // let prefix = "Hello" | starts_with(prefix, "He") → true
        let prog = ast_full("let prefix = \"Hello\" | starts_with(prefix, \"He\")");
        let last = prog.last().unwrap();
        assert_literal(last, "true", "Full: let+starts_with must fold");
    }

    #[test]
    fn full_pipeline_fold_then_dead_branch() {
        // let x = 5 | if (x == 5): "yes" else: "no"
        // Full: x substituted → if (true): "yes" → "yes"
        let prog = ast_full("let x = 5 | if (x == 5): \"yes\" else: \"no\"");
        let last = prog.last().unwrap();
        assert_literal(last, "yes", "Full: propagate+fold+dead-branch must yield \"yes\"");
    }

    #[test]
    fn basic_does_not_propagate_let() {
        // Basic does not do let-literal propagation.
        let prog = ast_basic("let x = 5 | if (x == 5): \"yes\" else: \"no\"");
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::If(_)),
            "Basic: let propagation must not happen, expected If, got {:?}",
            last.expr
        );
    }

    #[test]
    fn module_scoped_def_not_mistaken_for_builtin_shadow() {
        // A Def inside a Module body must not prevent folding of the same-named
        // builtin at the top level.
        let prog = ast_full("upcase(\"hello\") | module m: def upcase(x): x; end");
        // The upcase("hello") call at the top level should be folded.
        let first = &prog[0];
        assert_literal(
            first,
            "HELLO",
            "Full: module-internal def must not shadow top-level fold",
        );
    }

    // ---- len on bytes literal folds ----
    #[rstest]
    #[case("len(b\"hello\")", "5")]
    #[case("len(b\"\")", "0")]
    fn len_bytes_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    // ---- to_string on None and Bool folds ----
    #[rstest]
    #[case("to_string(None)", "")]
    fn to_string_none_folds(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    // ---- Bytes literal stays as Call for to_string (not foldable) ----
    #[test]
    fn to_string_bytes_not_folded() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("to_string(b\"hi\")", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: to_string(bytes) must stay as Call"
            );
        }
    }

    // ---- NaN-guarded arithmetic does not fold ----
    #[test]
    fn nan_arithmetic_not_folded() {
        // nan() is not a literal, so arithmetic on it cannot be constant-folded.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("floor(nan())", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: floor(nan()) must not fold"
            );
        }
    }

    // ---- substitute_literals into And/Or/Paren/Try/Break/InterpolatedString ----
    #[test]
    fn let_propagation_into_try_block() {
        // let x = "ok" | try: x catch: "err" — x is substituted, try is preserved because it might error.
        let prog = ast_full("let x = 5 | try: x catch: 0");
        assert_eq!(prog.len(), 2, "Full: let + try must produce 2 nodes");
    }

    #[test]
    fn let_propagation_into_interpolated_string() {
        // let x = "hi" | s"${x} world" → substitute x, fold to literal "hi world"
        let prog = ast_full("let x = \"hi\" | s\"${x} world\"");
        let last = prog.last().unwrap();
        assert_literal(last, "hi world", "Full: let+interpolated string must fold");
    }

    #[test]
    fn let_propagation_into_paren() {
        // let x = 3 | (x + 1) → substitute x=3, fold 3+1=4
        let prog = ast_full("let x = 3 | (x + 1)");
        let last = prog.last().unwrap();
        assert_literal(last, "4", "Full: let+paren must fold");
    }

    // ---- Dead-def after inlining multiple call sites ----
    #[test]
    fn two_call_sites_both_inlined_def_eliminated() {
        // inc is called twice — both sites get inlined, so def is eliminated.
        let prog = ast_full("def inc(x): x + 1; | inc(3) | inc(7)");
        assert!(
            !prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: Def with two inlined call sites must be eliminated"
        );
        let last = prog.last().unwrap();
        assert_literal(last, "8", "Full: inc(7) must fold to 8");
    }

    // ---- optimize_node handles While / Loop / Foreach / Assign ----
    #[test]
    fn optimize_while_folds_constant_in_body() {
        // while(true): 1 + 1 — body constant should fold.
        let prog = ast_basic("while(true): 1 + 1;");
        assert_eq!(prog.len(), 1);
        // The while node itself must remain (condition is not false-literal).
        assert!(
            matches!(&*prog[0].expr, Expr::While(..)),
            "Basic: while must remain when condition is dynamic-ish"
        );
    }

    #[test]
    fn optimize_try_with_constant_folds_body() {
        // try: 1 + 2 catch: 0 — body must fold to 3.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("try: 1 + 2 catch: 0", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            // The Try node remains because catch matters even when body is constant.
            assert!(
                matches!(&*prog[0].expr, Expr::Try(..)),
                "{level:?}: Try must remain; got {:?}",
                prog[0].expr
            );
        }
    }

    #[test]
    fn optimize_foreach_folds_constant_values() {
        // foreach(x, [1]): 2 + 3 — body constant 5 should fold.
        let prog = ast_basic("foreach(x, [1]): 2 + 3;");
        assert_eq!(prog.len(), 1, "Basic: foreach must be single node");
        let Expr::Foreach(_, _, body) = &*prog[0].expr else {
            panic!("expected Foreach");
        };
        assert!(
            body.iter().any(|n| matches!(&*n.expr, Expr::Literal(_))),
            "Basic: Foreach body must have folded constant"
        );
    }

    #[test]
    fn optimize_match_folds_constant_in_arms() {
        // match(1+2) do | 3: "three" | _: "other" end — condition 1+2 folds to 3.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("match(1 + 2) do | 3: \"three\" | _: \"other\" end", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            // The match node remains but its value should be folded.
            assert!(
                matches!(&*prog[0].expr, Expr::Match(..)),
                "{level:?}: Match must remain when value is not a pattern-eliminating literal"
            );
        }
    }

    // ---- algebraic identity for sub(x, 0) ----
    #[test]
    fn algebraic_identity_sub_zero() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(". - 0", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Self_),
                "{level:?}: . - 0 must fold to Self_"
            );
        }
    }

    // ---- EQ/NE fold across mixed literal types ----
    #[rstest]
    #[case("eq(1, \"one\")", "false")]
    #[case("ne(1, \"one\")", "true")]
    #[case("eq(None, None)", "true")]
    #[case("ne(None, 0)", "true")]
    fn eq_ne_cross_type_fold(#[case] query: &str, #[case] expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
            assert_literal(&prog[0], expected, &format!("{level:?}: {query}"));
        }
    }

    // ---- multiple user defs, some inlinable, some not ----
    #[test]
    fn mixed_inline_and_non_inline_defs() {
        // double is inlineable (simple); fact is recursive (not inlineable).
        let prog = ast_full(
            "def double(x): x * 2; | def fact(n): if (n == 0): 1 else: n * fact(n - 1); | double(3) | fact(4)",
        );
        // double(3) should be inlined and folded to 6.
        // fact(4) must remain as Call.
        assert!(
            prog.iter().any(|n| matches!(&*n.expr, Expr::Def(..))),
            "Full: recursive fact must be preserved"
        );
        let last = prog.last().unwrap();
        assert!(matches!(&*last.expr, Expr::Call(..)), "Full: fact(4) must stay as Call");
    }

    // ---- substitute_literals into a CallDynamic node ----
    #[test]
    fn let_propagation_into_selectorchain_body() {
        // Selector chains are scope-stopping nodes; let propagation doesn't cross them.
        let prog = ast_full("let x = 5 | .h1 | x + 0");
        // x+0 should fold to 5 (via propagation).
        let last = prog.last().unwrap();
        assert_literal(last, "5", "Full: let + selector + x+0 must fold");
    }

    // ---- literal_is_truthy for all variants ----
    #[rstest]
    #[case("\"\" && .", "false")] // empty string is falsy
    #[case("\"x\" && .", r#"."#)] // non-empty string is truthy — drops literal
    fn literal_is_truthy_string(#[case] query: &str, #[case] _expected: &str) {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with(query, level);
            assert_eq!(prog.len(), 1, "{level:?}: {query}");
        }
    }

    #[test]
    fn literal_is_truthy_zero_number_is_falsy() {
        // `0 && .` → falsy literal → short-circuit to false.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("0 && .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Literal(Literal::Bool(false))),
                "{level:?}: 0 && . must short-circuit to false"
            );
        }
    }

    #[test]
    fn literal_is_truthy_nonzero_number_is_truthy() {
        // `1 && .` → truthy literal dropped, remaining And([.]) emitted.
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("1 && .", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::And(_)),
                "{level:?}: 1 && . truthy lit must be dropped leaving And([.])"
            );
        }
    }

    // ---- coalesce with both dynamic operands: stays as Call ----
    #[test]
    fn coalesce_both_dynamic_stays_as_call() {
        for level in [OptimizationLevel::Basic, OptimizationLevel::Full] {
            let prog = ast_with("coalesce(., .)", level);
            assert_eq!(prog.len(), 1, "{level:?}");
            assert!(
                matches!(&*prog[0].expr, Expr::Call(..)),
                "{level:?}: coalesce(., .) with both dynamic must stay as Call"
            );
        }
    }

    // ---- def with default-param is not inlinable ----
    #[test]
    fn def_with_default_param_not_inlined() {
        let prog = ast_full("def greet(name, greeting = \"hello\"): greeting; | greet(\"world\")");
        // Has a default param → not inlineable.
        let last = prog.last().unwrap();
        assert!(
            matches!(&*last.expr, Expr::Call(..)),
            "Full: def with default param must not be inlined; expected Call"
        );
    }
}