1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
//! The MiniEval interpreter engine.
//!
//! This module implements the core evaluation logic for Typst macros,
//! including expression evaluation, control flow, and function calls.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use crate::features::refs::{citation_mode_from_typst_form, CitationMode, ReferenceType};
use indexmap::IndexMap;
use typst_syntax::ast::{self, AstNode};
use typst_syntax::{parse, parse_code, SyntaxKind, SyntaxNode};
use super::library::{call_builtin, call_calc, call_method, BuiltinResult};
use super::ops;
use super::scope::Scopes;
use super::value::{
bibliography_content_value, citation_content_value, label_content_value,
normalize_ref_target_text, reference_content_value, Alignment, Arguments, Closure, ContentNode,
Direction, EvalError, EvalErrorKind, EvalResult, HorizAlign, MathSegment, Selector, ShowRule,
SourceSpan, Value, VertAlign,
};
use super::vfs::{NoopVfs, VirtualFileSystem};
/// Maximum number of loop iterations (infinite loop protection).
const MAX_ITERATIONS: usize = 10_000;
/// Configuration for the MiniEval interpreter.
#[derive(Debug, Clone)]
pub struct EvalConfig {
/// If true, errors on undefined functions/methods cause evaluation to fail.
/// If false, they produce warnings and fallback to raw source output.
pub strict: bool,
/// Maximum recursion depth for function calls.
pub max_recursion_depth: usize,
/// Maximum iterations for loops (infinite loop protection).
pub max_iterations: usize,
}
impl Default for EvalConfig {
fn default() -> Self {
Self {
strict: false, // Default to compat mode for better user experience
// Use a conservative depth limit to prevent stack overflow on Windows
// (Windows has smaller default stack size than Linux/macOS)
max_recursion_depth: 64,
max_iterations: MAX_ITERATIONS,
}
}
}
impl EvalConfig {
/// Create a strict configuration (fail on unknown functions).
pub fn strict() -> Self {
Self {
strict: true,
..Default::default()
}
}
/// Create a compat/lenient configuration (fallback on unknown functions).
pub fn compat() -> Self {
Self {
strict: false,
..Default::default()
}
}
}
/// A warning that occurred during evaluation but didn't stop execution.
#[derive(Debug, Clone)]
pub struct EvalWarning {
/// The warning message
pub message: String,
/// Optional source span where the warning occurred
pub span: Option<SourceSpan>,
}
impl EvalWarning {
/// Create a new warning.
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
span: None,
}
}
/// Attach a span to this warning.
pub fn with_span(mut self, span: SourceSpan) -> Self {
self.span = Some(span);
self
}
}
/// The MiniEval interpreter.
///
/// This struct holds the state needed to evaluate Typst source code,
/// including variable bindings, control flow state, file system access,
/// and module caching.
pub struct MiniEval {
/// The scope stack for variable bindings
scopes: Scopes,
/// Current control flow state
flow: Option<FlowEvent>,
/// Virtual file system for module loading and data access
vfs: Arc<dyn VirtualFileSystem>,
/// Cache of loaded modules (path -> module scope)
module_cache: Arc<RwLock<HashMap<String, IndexMap<String, Value>>>>,
/// Current file path (for relative imports)
current_file: Option<String>,
/// Global state storage (for state() function)
state_store: HashMap<String, Value>,
/// Counter storage (for counter() function)
counter_store: HashMap<String, Vec<i64>>,
/// Configuration for evaluation behavior
config: EvalConfig,
/// Warnings accumulated during evaluation
warnings: Vec<EvalWarning>,
/// Registered show rules
show_rules: Vec<ShowRule>,
/// Current recursion depth (for infinite recursion protection)
current_depth: usize,
}
/// A control flow event that occurred during evaluation.
#[derive(Debug, Clone)]
enum FlowEvent {
/// Break out of a loop
Break,
/// Continue to next iteration
Continue,
/// Return from a function with an optional value
Return(Option<Value>),
}
impl MiniEval {
/// Create a new MiniEval interpreter with default (no-op) VFS and compat mode.
pub fn new() -> Self {
Self {
scopes: Scopes::new(),
flow: None,
vfs: Arc::new(NoopVfs),
module_cache: Arc::new(RwLock::new(HashMap::new())),
current_file: None,
state_store: HashMap::new(),
counter_store: HashMap::new(),
config: EvalConfig::default(),
warnings: Vec::new(),
show_rules: Vec::new(),
current_depth: 0,
}
}
/// Create a new MiniEval interpreter with a custom VFS.
pub fn with_vfs(vfs: Arc<dyn VirtualFileSystem>) -> Self {
Self {
scopes: Scopes::new(),
flow: None,
vfs,
module_cache: Arc::new(RwLock::new(HashMap::new())),
current_file: None,
state_store: HashMap::new(),
counter_store: HashMap::new(),
config: EvalConfig::default(),
warnings: Vec::new(),
show_rules: Vec::new(),
current_depth: 0,
}
}
/// Create a new MiniEval interpreter with custom config.
pub fn with_config(config: EvalConfig) -> Self {
Self {
scopes: Scopes::new(),
flow: None,
vfs: Arc::new(NoopVfs),
module_cache: Arc::new(RwLock::new(HashMap::new())),
current_file: None,
state_store: HashMap::new(),
counter_store: HashMap::new(),
config,
warnings: Vec::new(),
show_rules: Vec::new(),
current_depth: 0,
}
}
/// Create a new MiniEval interpreter with custom VFS and config.
pub fn with_vfs_and_config(vfs: Arc<dyn VirtualFileSystem>, config: EvalConfig) -> Self {
Self {
scopes: Scopes::new(),
flow: None,
vfs,
module_cache: Arc::new(RwLock::new(HashMap::new())),
current_file: None,
state_store: HashMap::new(),
counter_store: HashMap::new(),
config,
warnings: Vec::new(),
show_rules: Vec::new(),
current_depth: 0,
}
}
/// Set the current file path (for relative imports).
pub fn set_current_file(&mut self, path: impl Into<String>) {
self.current_file = Some(path.into());
}
/// Get a reference to the VFS.
pub fn vfs(&self) -> &Arc<dyn VirtualFileSystem> {
&self.vfs
}
/// Get the current configuration.
pub fn config(&self) -> &EvalConfig {
&self.config
}
/// Check if running in strict mode.
pub fn is_strict(&self) -> bool {
self.config.strict
}
/// Add a warning during evaluation.
pub fn warn(&mut self, message: impl Into<String>) {
self.warnings.push(EvalWarning::new(message));
}
/// Add a warning with span information.
pub fn warn_at(&mut self, message: impl Into<String>, span: SourceSpan) {
self.warnings
.push(EvalWarning::new(message).with_span(span));
}
/// Take all accumulated warnings.
pub fn take_warnings(&mut self) -> Vec<EvalWarning> {
std::mem::take(&mut self.warnings)
}
/// Get accumulated warnings (without taking them).
pub fn warnings(&self) -> &[EvalWarning] {
&self.warnings
}
// ========================================================================
// Show Rules
// ========================================================================
/// Register a show rule.
pub fn add_show_rule(&mut self, selector: Selector, transform: Arc<Closure>) {
let priority = self.show_rules.len();
self.show_rules
.push(ShowRule::new(selector, transform, priority));
}
/// Get registered show rules.
pub fn show_rules(&self) -> &[ShowRule] {
&self.show_rules
}
/// Apply show rules to content, transforming matching nodes.
///
/// This recursively traverses the content tree and applies matching rules.
/// Rules are applied in reverse priority order (later rules take precedence).
pub fn apply_show_rules(&mut self, content: Vec<ContentNode>) -> EvalResult<Vec<ContentNode>> {
let mut result = Vec::new();
for node in content {
// Find the first matching rule (by highest priority)
let matching_rule = self
.show_rules
.iter()
.rev()
.find(|rule| rule.selector.matches(&node))
.cloned();
if let Some(rule) = matching_rule {
// The transform function receives the matched content as "it"
// For MVP, we pass the node as a Value
let node_value = Value::Content(vec![node.clone()]);
// Create a scope with "it" bound to the matched content
self.scopes.enter();
self.scopes.define("it".to_string(), node_value);
// Call the closure with no explicit args (it uses "it" from scope)
let body_result = self.call_closure_inner(&rule.transform);
self.scopes.exit();
// Convert result to content
match body_result {
Ok(Value::Content(nodes)) => {
result.extend(nodes);
}
Ok(other) => {
// Convert other values to text content
result.push(ContentNode::Text(other.display()));
}
Err(_) => {
// On error, keep the original node
result.push(node);
}
}
} else {
// No matching rule, recursively process children
let processed = self.process_content_children(node)?;
result.push(processed);
}
}
Ok(result)
}
/// Call a closure's body without binding parameters (assumes scope is set up).
fn call_closure_inner(&mut self, closure: &Closure) -> EvalResult<Value> {
// Parse and evaluate the body
let body_source = &closure.body_source;
let root = parse_code(body_source);
if root.erroneous() {
return Err(EvalError::syntax("Failed to parse closure body"));
}
// Find and evaluate the expression
if let Some(expr) = root.cast::<ast::Expr>() {
self.eval_expr(expr)
} else if let Some(code) = root.cast::<ast::Code>() {
self.eval_code(code)
} else {
Ok(Value::None)
}
}
/// Recursively process children of a content node.
fn process_content_children(&mut self, node: ContentNode) -> EvalResult<ContentNode> {
match node {
ContentNode::Strong(children) => {
let processed = self.apply_show_rules(children)?;
Ok(ContentNode::Strong(processed))
}
ContentNode::Emph(children) => {
let processed = self.apply_show_rules(children)?;
Ok(ContentNode::Emph(processed))
}
ContentNode::Heading { level, content } => {
let processed = self.apply_show_rules(content)?;
Ok(ContentNode::Heading {
level,
content: processed,
})
}
ContentNode::ListItem(children) => {
let processed = self.apply_show_rules(children)?;
Ok(ContentNode::ListItem(processed))
}
ContentNode::EnumItem { number, content } => {
let processed = self.apply_show_rules(content)?;
Ok(ContentNode::EnumItem {
number,
content: processed,
})
}
// Other nodes don't have children to process
other => Ok(other),
}
}
/// Evaluate markup (the top-level content).
pub fn eval_markup(&mut self, markup: ast::Markup) -> EvalResult<Value> {
let mut output = Value::None;
for expr in markup.exprs() {
let value = self.eval_expr(expr)?;
output = ops::join(output, value)?;
if self.flow.is_some() {
break;
}
}
Ok(output)
}
/// Evaluate an expression.
/// Evaluate an expression.
///
/// This is the main expression dispatcher. Each expression type is routed
/// to a dedicated handler method for clarity and testability.
pub fn eval_expr(&mut self, expr: ast::Expr) -> EvalResult<Value> {
match expr {
// ================================================================
// Literals (primitives)
// ================================================================
ast::Expr::None(_)
| ast::Expr::Auto(_)
| ast::Expr::Bool(_)
| ast::Expr::Int(_)
| ast::Expr::Float(_)
| ast::Expr::Str(_) => self.eval_literal(expr),
// ================================================================
// Identifiers
// ================================================================
ast::Expr::Ident(ident) => self.eval_ident(ident),
// ================================================================
// Collections (Array, Dict)
// ================================================================
ast::Expr::Array(arr) => self.eval_array(arr),
ast::Expr::Dict(dict) => self.eval_dict(dict),
// ================================================================
// Blocks and Parenthesized Expressions
// ================================================================
ast::Expr::CodeBlock(block) => self.eval_code_block(block),
ast::Expr::ContentBlock(block) => self.eval_content_block(block),
ast::Expr::Parenthesized(paren) => self.eval_expr(paren.expr()),
// ================================================================
// Operators (Unary, Binary)
// ================================================================
ast::Expr::Unary(unary) => self.eval_unary(unary),
ast::Expr::Binary(binary) => self.eval_binary(binary),
// ================================================================
// Control Flow (Conditional, Loops, Break/Continue/Return)
// ================================================================
ast::Expr::Conditional(cond) => self.eval_conditional(cond),
ast::Expr::WhileLoop(while_loop) => self.eval_while(while_loop),
ast::Expr::ForLoop(for_loop) => self.eval_for(for_loop),
ast::Expr::LoopBreak(_) => self.handle_loop_break(),
ast::Expr::LoopContinue(_) => self.handle_loop_continue(),
ast::Expr::FuncReturn(ret) => self.handle_func_return(ret),
// ================================================================
// Bindings and Functions
// ================================================================
ast::Expr::LetBinding(binding) => self.eval_let(binding),
ast::Expr::FuncCall(call) => self.eval_func_call(call),
ast::Expr::Closure(closure) => self.eval_closure(closure),
// ================================================================
// Field Access
// ================================================================
ast::Expr::FieldAccess(access) => self.eval_field_access(access),
// ================================================================
// Markup Elements
// ================================================================
ast::Expr::Text(_)
| ast::Expr::Space(_)
| ast::Expr::Linebreak(_)
| ast::Expr::Parbreak(_)
| ast::Expr::Strong(_)
| ast::Expr::Emph(_)
| ast::Expr::Heading(_)
| ast::Expr::ListItem(_)
| ast::Expr::EnumItem(_)
| ast::Expr::Raw(_)
| ast::Expr::Equation(_)
| ast::Expr::Math(_)
| ast::Expr::Label(_)
| ast::Expr::Ref(_)
| ast::Expr::Escape(_)
| ast::Expr::Shorthand(_) => self.eval_markup_element(expr),
// ================================================================
// Module System (Import, Include)
// ================================================================
ast::Expr::ModuleImport(import) => self.eval_import(import),
ast::Expr::ModuleInclude(include) => self.eval_include(include),
// ================================================================
// Passthrough (unevaluated, preserved as raw source)
// ================================================================
ast::Expr::SetRule(_)
| ast::Expr::ShowRule(_)
| ast::Expr::Contextual(_)
| ast::Expr::DestructAssignment(_) => self.passthrough_expr(&expr),
// Fallback for any unhandled expression types
_ => self.passthrough_expr(&expr),
}
}
// ========================================================================
// Control Flow Helpers
// ========================================================================
/// Handle `break` statement in loops.
fn handle_loop_break(&mut self) -> EvalResult<Value> {
self.flow = Some(FlowEvent::Break);
Ok(Value::None)
}
/// Handle `continue` statement in loops.
fn handle_loop_continue(&mut self) -> EvalResult<Value> {
self.flow = Some(FlowEvent::Continue);
Ok(Value::None)
}
/// Handle `return` statement in functions.
fn handle_func_return(&mut self, ret: ast::FuncReturn) -> EvalResult<Value> {
let value = ret.body().map(|e| self.eval_expr(e)).transpose()?;
self.flow = Some(FlowEvent::Return(value));
Ok(Value::None)
}
/// Passthrough expression as raw source (for unevaluated expressions).
fn passthrough_expr(&self, expr: &ast::Expr) -> EvalResult<Value> {
let source = expr.to_untyped().text().to_string();
Ok(Value::Content(vec![ContentNode::RawSource(source)]))
}
/// Evaluate literal expressions (None, Auto, Bool, Int, Float, Str).
fn eval_literal(&mut self, expr: ast::Expr) -> EvalResult<Value> {
match expr {
ast::Expr::None(_) => Ok(Value::None),
ast::Expr::Auto(_) => Ok(Value::Auto),
ast::Expr::Bool(b) => Ok(Value::Bool(b.get())),
ast::Expr::Int(i) => Ok(Value::Int(i.get())),
ast::Expr::Float(f) => Ok(Value::Float(f.get())),
ast::Expr::Str(s) => Ok(Value::Str(s.get().to_string())),
_ => unreachable!("eval_literal called with non-literal"),
}
}
/// Evaluate markup element expressions (Text, Space, Strong, Emph, etc.).
fn eval_markup_element(&mut self, expr: ast::Expr) -> EvalResult<Value> {
match expr {
ast::Expr::Text(text) => Ok(Value::Content(vec![ContentNode::Text(
text.get().to_string(),
)])),
ast::Expr::Space(_) => Ok(Value::Content(vec![ContentNode::Space])),
ast::Expr::Linebreak(_) => Ok(Value::Content(vec![ContentNode::Linebreak])),
ast::Expr::Parbreak(_) => Ok(Value::Content(vec![ContentNode::Parbreak])),
ast::Expr::Strong(strong) => {
let body = self.eval_markup(strong.body())?;
Ok(Value::Content(vec![ContentNode::Strong(
body.into_content(),
)]))
}
ast::Expr::Emph(emph) => {
let body = self.eval_markup(emph.body())?;
Ok(Value::Content(vec![ContentNode::Emph(body.into_content())]))
}
ast::Expr::Heading(heading) => {
let level = heading.depth().get() as u8;
let body = self.eval_markup(heading.body())?;
Ok(Value::Content(vec![ContentNode::Heading {
level,
content: body.into_content(),
}]))
}
ast::Expr::ListItem(item) => {
let body = self.eval_markup(item.body())?;
Ok(Value::Content(vec![ContentNode::ListItem(
body.into_content(),
)]))
}
ast::Expr::EnumItem(item) => {
let number = item.number();
let body = self.eval_markup(item.body())?;
Ok(Value::Content(vec![ContentNode::EnumItem {
number: number.map(|n| n as i64),
content: body.into_content(),
}]))
}
ast::Expr::Raw(raw) => {
let text: String = raw
.lines()
.map(|l| l.get().to_string())
.collect::<Vec<_>>()
.join("\n");
let lang = raw.lang().map(|l| l.get().to_string());
let block = raw.block();
Ok(Value::Content(vec![ContentNode::Raw { text, lang, block }]))
}
ast::Expr::Equation(eq) => {
// Evaluate hash expressions inside math content
let segments = self.eval_math_content(eq.body().to_untyped())?;
let block = eq.block();
Ok(Value::Content(vec![ContentNode::Math { segments, block }]))
}
ast::Expr::Math(math) => {
// Evaluate hash expressions inside math content
let segments = self.eval_math_content(math.to_untyped())?;
Ok(Value::Content(vec![ContentNode::Math {
segments,
block: false,
}]))
}
ast::Expr::Label(label) => Ok(Value::Content(vec![ContentNode::Label(
label.get().to_string(),
)])),
ast::Expr::Ref(reference) => Ok(Value::Content(vec![ContentNode::Reference {
target: reference.target().to_string(),
ref_type: ReferenceType::Basic,
}])),
ast::Expr::Escape(esc) => Ok(Value::Content(vec![ContentNode::Text(
esc.get().to_string(),
)])),
ast::Expr::Shorthand(sh) => Ok(Value::Content(vec![ContentNode::Text(
sh.get().to_string(),
)])),
_ => unreachable!("eval_markup_element called with non-markup"),
}
}
/// Evaluate a module import.
fn eval_import(&mut self, import: ast::ModuleImport) -> EvalResult<Value> {
let source_expr = import.source();
let source_val = self.eval_expr(source_expr)?;
let path = source_val.as_str()?;
let current_dir = if let Some(cf) = &self.current_file {
std::path::Path::new(cf)
.parent()
.unwrap_or(std::path::Path::new(""))
.to_str()
.unwrap_or(".")
} else {
"."
};
let resolved_path = self
.vfs
.resolve(current_dir, path)
.map_err(|e| EvalError::other(e.to_string()))?;
// Check cache - clone the module to avoid holding the lock
let cached_module = {
if let Ok(cache) = self.module_cache.read() {
cache.get(&resolved_path).cloned()
} else {
None
}
};
if let Some(module) = cached_module {
if let Some(new_name) = import.new_name() {
let module_val = Value::Dict(module.clone());
self.scopes.define(new_name.get().to_string(), module_val);
} else if let Some(imports) = import.imports() {
self.bind_imports(Some(imports), &module)?;
}
return Ok(Value::None);
}
// Load and evaluate
let content = self
.vfs
.read_text(&resolved_path)
.map_err(|e| EvalError::other(e.to_string()))?;
let mut sub_eval = MiniEval {
scopes: Scopes::new(),
flow: None,
vfs: self.vfs.clone(),
module_cache: self.module_cache.clone(),
current_file: Some(resolved_path.clone()),
state_store: self.state_store.clone(),
counter_store: self.counter_store.clone(),
config: self.config.clone(),
warnings: Vec::new(),
show_rules: self.show_rules.clone(),
current_depth: self.current_depth, // Inherit depth from parent
};
let root = parse(&content);
if !root.errors().is_empty() {
return Err(EvalError::syntax(format!(
"In module {}: parse error",
path
)));
}
if let Some(markup) = root.cast::<ast::Markup>() {
sub_eval.eval_markup(markup)?;
}
let exports = sub_eval.scopes.top_bindings();
// Update cache
if let Ok(mut cache) = self.module_cache.write() {
cache.insert(resolved_path, exports.clone());
}
if let Some(new_name) = import.new_name() {
let module_val = Value::Dict(exports.clone());
self.scopes.define(new_name.get().to_string(), module_val);
} else if let Some(imports) = import.imports() {
self.bind_imports(Some(imports), &exports)?;
}
Ok(Value::None)
}
/// Evaluate a module include.
fn eval_include(&mut self, include: ast::ModuleInclude) -> EvalResult<Value> {
let source_expr = include.source();
let source_val = self.eval_expr(source_expr)?;
let path = source_val.as_str()?;
let current_dir = if let Some(cf) = &self.current_file {
std::path::Path::new(cf)
.parent()
.unwrap_or(std::path::Path::new(""))
.to_str()
.unwrap_or(".")
} else {
"."
};
let resolved_path = self
.vfs
.resolve(current_dir, path)
.map_err(|e| EvalError::other(e.to_string()))?;
let content = self
.vfs
.read_text(&resolved_path)
.map_err(|e| EvalError::other(e.to_string()))?;
// Include evaluates content and returns it
let mut sub_eval = MiniEval {
scopes: Scopes::new(),
flow: None,
vfs: self.vfs.clone(),
module_cache: self.module_cache.clone(),
current_file: Some(resolved_path.clone()),
state_store: self.state_store.clone(),
counter_store: self.counter_store.clone(),
config: self.config.clone(),
warnings: Vec::new(),
show_rules: self.show_rules.clone(),
current_depth: self.current_depth, // Inherit depth from parent
};
let root = parse(&content);
if !root.errors().is_empty() {
return Err(EvalError::syntax(format!(
"In included file {}: parse error",
path
)));
}
if let Some(markup) = root.cast::<ast::Markup>() {
sub_eval.eval_markup(markup)
} else {
Ok(Value::None)
}
}
fn bind_imports(
&mut self,
imports: Option<ast::Imports>,
module: &IndexMap<String, Value>,
) -> EvalResult<()> {
if let Some(imports) = imports {
match imports {
ast::Imports::Wildcard => {
for (name, val) in module {
self.scopes.define(name.clone(), val.clone());
}
}
ast::Imports::Items(items) => {
for item in items.iter() {
let original_name = item.original_name().get().as_str();
if let Some(val) = module.get(original_name) {
// bound_name() returns the name to bind to (same as original for simple imports)
let bound_name = item.bound_name().get().as_str();
self.scopes.define(bound_name.to_string(), val.clone());
} else {
return Err(EvalError::undefined(format!(
"Module does not export '{}'",
original_name
)));
}
}
}
}
}
Ok(())
}
/// Evaluate an identifier.
fn eval_ident(&self, ident: ast::Ident) -> EvalResult<Value> {
let name = ident.get().as_str();
let span = SourceSpan::from_typst_span(ident.span());
// First check scopes
if let Some(value) = self.scopes.get(name) {
return Ok(value.clone());
}
// Then check built-in constants
match name {
// Keywords
"none" => Ok(Value::None),
"auto" => Ok(Value::Auto),
"true" => Ok(Value::Bool(true)),
"false" => Ok(Value::Bool(false)),
// Alignment constants
"left" => Ok(Value::Alignment(Alignment::new(
Some(HorizAlign::Left),
None,
))),
"right" => Ok(Value::Alignment(Alignment::new(
Some(HorizAlign::Right),
None,
))),
"center" => Ok(Value::Alignment(Alignment::new(
Some(HorizAlign::Center),
None,
))),
"start" => Ok(Value::Alignment(Alignment::new(
Some(HorizAlign::Start),
None,
))),
"end" => Ok(Value::Alignment(Alignment::new(
Some(HorizAlign::End),
None,
))),
"top" => Ok(Value::Alignment(Alignment::new(None, Some(VertAlign::Top)))),
"bottom" => Ok(Value::Alignment(Alignment::new(
None,
Some(VertAlign::Bottom),
))),
"horizon" => Ok(Value::Alignment(Alignment::new(
None,
Some(VertAlign::Horizon),
))),
// Direction constants
"ltr" => Ok(Value::Direction(Direction::Ltr)),
"rtl" => Ok(Value::Direction(Direction::Rtl)),
"ttb" => Ok(Value::Direction(Direction::Ttb)),
"btt" => Ok(Value::Direction(Direction::Btt)),
// Builtin functions - return as a function value
_ if self.is_builtin_function(name) => {
Ok(Value::Func(Arc::new(self.create_builtin_wrapper(name))))
}
// Unknown - error with span
_ => {
let err = EvalError::undefined(name);
Err(if let Some(s) = span {
err.with_span(s)
} else {
err
})
}
}
}
/// Evaluate an array literal.
fn eval_array(&mut self, arr: ast::Array) -> EvalResult<Value> {
let mut result = Vec::new();
for item in arr.items() {
match item {
ast::ArrayItem::Pos(expr) => {
result.push(self.eval_expr(expr)?);
}
ast::ArrayItem::Spread(spread) => {
let value = self.eval_expr(spread.expr())?;
match value {
Value::Array(arr) => result.extend(arr),
Value::None => {}
_ => {
return Err(EvalError::invalid_op(format!(
"cannot spread {} into array",
value.type_name()
)))
}
}
}
}
}
Ok(Value::Array(result))
}
/// Evaluate a dictionary literal.
fn eval_dict(&mut self, dict: ast::Dict) -> EvalResult<Value> {
let mut result = IndexMap::new();
for item in dict.items() {
match item {
ast::DictItem::Named(named) => {
let key = named.name().get().to_string();
let value = self.eval_expr(named.expr())?;
result.insert(key, value);
}
ast::DictItem::Keyed(keyed) => {
let key = self.eval_expr(keyed.key())?.as_str()?.to_string();
let value = self.eval_expr(keyed.expr())?;
result.insert(key, value);
}
ast::DictItem::Spread(spread) => {
let value = self.eval_expr(spread.expr())?;
match value {
Value::Dict(d) => result.extend(d),
Value::None => {}
_ => {
return Err(EvalError::invalid_op(format!(
"cannot spread {} into dictionary",
value.type_name()
)))
}
}
}
}
}
Ok(Value::Dict(result))
}
/// Evaluate a code block.
fn eval_code_block(&mut self, block: ast::CodeBlock) -> EvalResult<Value> {
self.scopes.enter();
let result = self.eval_code(block.body())?;
self.scopes.exit();
Ok(result)
}
/// Evaluate code (a sequence of expressions).
fn eval_code(&mut self, code: ast::Code) -> EvalResult<Value> {
let mut output = Value::None;
for expr in code.exprs() {
let value = self.eval_expr(expr)?;
output = ops::join(output, value)?;
if self.flow.is_some() {
break;
}
}
Ok(output)
}
/// Evaluate a content block.
fn eval_content_block(&mut self, block: ast::ContentBlock) -> EvalResult<Value> {
self.scopes.enter();
let result = self.eval_markup(block.body())?;
self.scopes.exit();
Ok(result)
}
/// Evaluate a unary operation.
fn eval_unary(&mut self, unary: ast::Unary) -> EvalResult<Value> {
let value = self.eval_expr(unary.expr())?;
match unary.op() {
ast::UnOp::Pos => ops::pos(value),
ast::UnOp::Neg => ops::neg(value),
ast::UnOp::Not => ops::not(&value),
}
}
/// Evaluate a binary operation.
fn eval_binary(&mut self, binary: ast::Binary) -> EvalResult<Value> {
let op = binary.op();
// Extract span for error reporting
let span = SourceSpan::from_typst_span(binary.span());
// Helper to attach span to errors
let attach_span = |result: EvalResult<Value>| -> EvalResult<Value> {
result.map_err(|e| {
if let Some(s) = span {
e.with_span(s)
} else {
e
}
})
};
// Handle assignment operators specially (don't evaluate LHS first)
if op == ast::BinOp::Assign {
return attach_span(self.eval_assign(binary.lhs(), binary.rhs()));
}
if matches!(
op,
ast::BinOp::AddAssign
| ast::BinOp::SubAssign
| ast::BinOp::MulAssign
| ast::BinOp::DivAssign
) {
return attach_span(self.eval_compound_assign(binary.lhs(), binary.rhs(), op));
}
// Short-circuit evaluation for logical operators
if op == ast::BinOp::And {
let lhs = attach_span(self.eval_expr(binary.lhs()))?.as_bool()?;
if !lhs {
return Ok(Value::Bool(false));
}
let rhs = attach_span(self.eval_expr(binary.rhs()))?.as_bool()?;
return Ok(Value::Bool(rhs));
}
if op == ast::BinOp::Or {
let lhs = attach_span(self.eval_expr(binary.lhs()))?.as_bool()?;
if lhs {
return Ok(Value::Bool(true));
}
let rhs = attach_span(self.eval_expr(binary.rhs()))?.as_bool()?;
return Ok(Value::Bool(rhs));
}
let lhs = self.eval_expr(binary.lhs())?;
let rhs = self.eval_expr(binary.rhs())?;
attach_span(match op {
ast::BinOp::Add => ops::add(lhs, rhs),
ast::BinOp::Sub => ops::sub(lhs, rhs),
ast::BinOp::Mul => ops::mul(lhs, rhs),
ast::BinOp::Div => ops::div(lhs, rhs),
// Note: Typst doesn't have % operator in syntax, modulo is done via calc.rem()
ast::BinOp::Eq => Ok(Value::Bool(ops::eq(&lhs, &rhs))),
ast::BinOp::Neq => Ok(Value::Bool(ops::ne(&lhs, &rhs))),
ast::BinOp::Lt => Ok(Value::Bool(ops::lt(&lhs, &rhs)?)),
ast::BinOp::Leq => Ok(Value::Bool(ops::le(&lhs, &rhs)?)),
ast::BinOp::Gt => Ok(Value::Bool(ops::gt(&lhs, &rhs)?)),
ast::BinOp::Geq => Ok(Value::Bool(ops::ge(&lhs, &rhs)?)),
ast::BinOp::In => ops::contains(&rhs, &lhs).map(Value::Bool),
ast::BinOp::NotIn => ops::contains(&rhs, &lhs).map(|b| Value::Bool(!b)),
ast::BinOp::And | ast::BinOp::Or => unreachable!(), // Handled above
ast::BinOp::Assign
| ast::BinOp::AddAssign
| ast::BinOp::SubAssign
| ast::BinOp::MulAssign
| ast::BinOp::DivAssign => unreachable!(), // Handled above
})
}
/// Evaluate a simple assignment: `variable = value`
///
/// In Typst, assignments return `none`, not the assigned value.
fn eval_assign(&mut self, lhs: ast::Expr, rhs: ast::Expr) -> EvalResult<Value> {
let name = match lhs {
ast::Expr::Ident(ident) => ident.get().to_string(),
_ => {
return Err(EvalError::invalid_op(
"assignment target must be an identifier".to_string(),
))
}
};
let value = self.eval_expr(rhs)?;
self.scopes.assign(&name, value)?;
Ok(Value::None) // Assignments return none in Typst
}
/// Evaluate a compound assignment: `variable += value`, etc.
///
/// In Typst, assignments return `none`, not the assigned value.
fn eval_compound_assign(
&mut self,
lhs: ast::Expr,
rhs: ast::Expr,
op: ast::BinOp,
) -> EvalResult<Value> {
let name = match lhs {
ast::Expr::Ident(ident) => ident.get().to_string(),
_ => {
return Err(EvalError::invalid_op(
"assignment target must be an identifier".to_string(),
))
}
};
let current = self.scopes.get_or_err(&name)?.clone();
let rhs_val = self.eval_expr(rhs)?;
let new_value = match op {
ast::BinOp::AddAssign => ops::add(current, rhs_val)?,
ast::BinOp::SubAssign => ops::sub(current, rhs_val)?,
ast::BinOp::MulAssign => ops::mul(current, rhs_val)?,
ast::BinOp::DivAssign => ops::div(current, rhs_val)?,
_ => unreachable!(),
};
self.scopes.assign(&name, new_value)?;
Ok(Value::None) // Assignments return none in Typst
}
/// Evaluate a conditional expression.
fn eval_conditional(&mut self, cond: ast::Conditional) -> EvalResult<Value> {
let condition = self.eval_expr(cond.condition())?.as_bool()?;
if condition {
self.eval_expr(cond.if_body())
} else if let Some(else_body) = cond.else_body() {
self.eval_expr(else_body)
} else {
Ok(Value::None)
}
}
/// Evaluate a while loop.
fn eval_while(&mut self, while_loop: ast::WhileLoop) -> EvalResult<Value> {
let mut output = Value::None;
let mut iterations = 0;
loop {
if iterations >= self.config.max_iterations {
return Err(EvalError::too_many_iterations());
}
let condition = self.eval_expr(while_loop.condition())?.as_bool()?;
if !condition {
break;
}
let value = self.eval_expr(while_loop.body())?;
output = ops::join(output, value)?;
match &self.flow {
Some(FlowEvent::Break) => {
self.flow = None;
break;
}
Some(FlowEvent::Continue) => {
self.flow = None;
}
Some(FlowEvent::Return(_)) => break,
None => {}
}
iterations += 1;
}
Ok(output)
}
/// Evaluate a for loop.
fn eval_for(&mut self, for_loop: ast::ForLoop) -> EvalResult<Value> {
let iterable = self.eval_expr(for_loop.iterable())?;
let pattern = for_loop.pattern();
let body = for_loop.body();
let items: Vec<Value> = match iterable {
Value::Array(arr) => arr,
Value::Dict(dict) => dict
.into_iter()
.map(|(k, v)| Value::Array(vec![Value::Str(k), v]))
.collect(),
Value::Str(s) => s.chars().map(|c| Value::Str(c.to_string())).collect(),
_ => {
return Err(EvalError::invalid_op(format!(
"cannot iterate over {}",
iterable.type_name()
)))
}
};
let mut output = Value::None;
self.scopes.enter();
for (i, item) in items.into_iter().enumerate() {
if i >= self.config.max_iterations {
self.scopes.exit();
return Err(EvalError::too_many_iterations());
}
self.destructure(pattern, item)?;
let value = self.eval_expr(body)?;
output = ops::join(output, value)?;
match &self.flow {
Some(FlowEvent::Break) => {
self.flow = None;
break;
}
Some(FlowEvent::Continue) => {
self.flow = None;
}
Some(FlowEvent::Return(_)) => break,
None => {}
}
}
self.scopes.exit();
Ok(output)
}
/// Destructure a value into a pattern.
fn destructure(&mut self, pattern: ast::Pattern, value: Value) -> EvalResult<()> {
match pattern {
ast::Pattern::Normal(ast::Expr::Ident(ident)) => {
self.scopes.define(ident.get().to_string(), value);
Ok(())
}
ast::Pattern::Placeholder(_) => Ok(()),
ast::Pattern::Parenthesized(paren) => self.destructure(paren.pattern(), value),
ast::Pattern::Destructuring(destruct) => {
let items: Vec<ast::DestructuringItem> = destruct.items().collect();
match value {
Value::Array(arr) => {
let mut arr_iter = arr.into_iter();
for item in items {
match item {
ast::DestructuringItem::Pattern(pat) => {
let v = arr_iter.next().unwrap_or(Value::None);
self.destructure(pat, v)?;
}
ast::DestructuringItem::Spread(spread) => {
let rest: Vec<Value> = arr_iter.collect();
if let Some(ast::Expr::Ident(ident)) = spread.sink_expr() {
self.scopes
.define(ident.get().to_string(), Value::Array(rest));
}
break;
}
ast::DestructuringItem::Named(_) => {
return Err(EvalError::invalid_op(
"cannot destructure named pattern from array".to_string(),
))
}
}
}
Ok(())
}
Value::Dict(dict) => {
for item in items {
match item {
ast::DestructuringItem::Pattern(ast::Pattern::Normal(
ast::Expr::Ident(ident),
)) => {
let key = ident.get().as_str();
let v = dict.get(key).cloned().unwrap_or(Value::None);
self.scopes.define(key.to_string(), v);
}
ast::DestructuringItem::Named(named) => {
let key = named.name().get().to_string();
let v = dict.get(&key).cloned().unwrap_or(Value::None);
self.destructure(named.pattern(), v)?;
}
ast::DestructuringItem::Spread(spread) => {
if let Some(ast::Expr::Ident(ident)) = spread.sink_expr() {
self.scopes.define(
ident.get().to_string(),
Value::Dict(dict.clone()),
);
}
}
_ => {}
}
}
Ok(())
}
_ => Err(EvalError::invalid_op(format!(
"cannot destructure {}",
value.type_name()
))),
}
}
ast::Pattern::Normal(expr) => Err(EvalError::invalid_op(format!(
"cannot assign to expression: {}",
expr.to_untyped().text()
))),
}
}
/// Evaluate a let binding.
fn eval_let(&mut self, binding: ast::LetBinding) -> EvalResult<Value> {
let value = match binding.init() {
Some(expr) => self.eval_expr(expr)?,
None => Value::None,
};
match binding.kind() {
ast::LetBindingKind::Normal(pattern) => {
self.destructure(pattern, value)?;
}
ast::LetBindingKind::Closure(ident) => {
// This is a function definition: #let f(x) = ...
// The value should already be a closure
self.scopes.define(ident.get().to_string(), value);
}
}
Ok(Value::None)
}
/// Evaluate a closure definition.
///
/// Note: Due to limitations in how typst-syntax nodes work (text is detached
/// when nodes are extracted), we need to get the body source from the original
/// input. This is handled by storing the body in a special way.
fn eval_closure(&mut self, closure: ast::Closure) -> EvalResult<Value> {
use typst_syntax::ast::AstNode;
// Helper to recursively collect text from syntax nodes
fn collect_text(node: &typst_syntax::SyntaxNode) -> String {
if node.children().len() == 0 {
node.text().to_string()
} else {
node.children().map(collect_text).collect()
}
}
let mut params = Vec::new();
let mut defaults = Vec::new();
let mut sink = None;
for param in closure.params().children() {
match param {
ast::Param::Pos(pattern) => {
if let ast::Pattern::Normal(ast::Expr::Ident(ident)) = pattern {
params.push(ident.get().to_string());
defaults.push(None);
}
}
ast::Param::Named(named) => {
params.push(named.name().get().to_string());
// Store source text instead of evaluating - enables lazy defaults
// that can depend on prior parameters: `#let f(x, y: x + 1) = ...`
// Use collect_text to handle complex expressions (binary ops, etc.)
let default_source = collect_text(named.expr().to_untyped());
defaults.push(Some(default_source));
}
ast::Param::Spread(spread) => {
// Sink argument - captures extra positional arguments
if let Some(sink_ident) = spread.sink_ident() {
sink = Some(sink_ident.get().to_string());
}
}
}
}
let body_source = collect_text(closure.body().to_untyped());
let captures = self.scopes.capture_all();
Ok(Value::Func(Arc::new(Closure {
name: None,
params,
defaults,
sink,
body_source,
captures,
})))
}
fn eval_ref_target_value(&mut self, value: Value) -> EvalResult<String> {
let raw = match value {
Value::Label(label) => label,
Value::Str(text) => text,
Value::Content(nodes) if nodes.len() == 1 => match &nodes[0] {
ContentNode::Label(label) | ContentNode::LabelDef(label) => label.clone(),
ContentNode::Text(text) => text.clone(),
_ => nodes[0].to_typst(),
},
Value::Content(nodes) => nodes.iter().map(|n| n.to_typst()).collect::<String>(),
other => other.display(),
};
Ok(normalize_ref_target_text(&raw))
}
fn eval_ref_target_expr(&mut self, expr: ast::Expr) -> EvalResult<String> {
let value = self.eval_expr(expr)?;
self.eval_ref_target_value(value)
}
fn eval_semantic_text_expr(&mut self, expr: ast::Expr) -> EvalResult<String> {
match expr {
ast::Expr::Ident(ident) => Ok(ident.get().to_string()),
other => {
let value = self.eval_expr(other)?;
self.eval_ref_target_value(value)
}
}
}
fn eval_semantic_cite(&mut self, args: ast::Args) -> EvalResult<Value> {
let mut keys = Vec::new();
let mut mode = CitationMode::Normal;
let mut supplement = None;
for arg in args.items() {
match arg {
ast::Arg::Pos(expr) => {
let key = self.eval_ref_target_expr(expr)?;
if !key.is_empty() {
keys.push(key);
}
}
ast::Arg::Named(named) => match named.name().get().as_str() {
"form" => {
let form = self.eval_semantic_text_expr(named.expr())?;
mode = citation_mode_from_typst_form(Some(form.as_str()));
}
"supplement" => {
let text = self.eval_semantic_text_expr(named.expr())?;
if !text.is_empty() {
supplement = Some(
text.trim_start_matches('[')
.trim_end_matches(']')
.trim()
.to_string(),
);
}
}
_ => {}
},
ast::Arg::Spread(_) => {
return Err(EvalError::argument(
"cite does not support spread arguments in MiniEval semantic mode"
.to_string(),
));
}
}
}
citation_content_value(keys, mode, supplement)
}
fn eval_semantic_ref(&mut self, args: ast::Args) -> EvalResult<Value> {
let mut items = args.items();
let first = items
.next()
.ok_or_else(|| EvalError::argument("ref expects 1 label argument".to_string()))?;
if items.next().is_some() {
return Err(EvalError::argument(
"ref expects exactly 1 label argument".to_string(),
));
}
let target = match first {
ast::Arg::Pos(expr) => self.eval_ref_target_expr(expr)?,
ast::Arg::Named(_) | ast::Arg::Spread(_) => {
return Err(EvalError::argument(
"ref expects 1 positional label argument".to_string(),
))
}
};
Ok(reference_content_value(target, ReferenceType::Basic))
}
fn eval_semantic_label(&mut self, args: ast::Args) -> EvalResult<Value> {
let mut items = args.items();
let first = items
.next()
.ok_or_else(|| EvalError::argument("label expects 1 label argument".to_string()))?;
if items.next().is_some() {
return Err(EvalError::argument(
"label expects exactly 1 label argument".to_string(),
));
}
let label = match first {
ast::Arg::Pos(expr) => self.eval_ref_target_expr(expr)?,
ast::Arg::Named(_) | ast::Arg::Spread(_) => {
return Err(EvalError::argument(
"label expects 1 positional label argument".to_string(),
))
}
};
Ok(label_content_value(label))
}
fn eval_semantic_bibliography(&mut self, args: ast::Args) -> EvalResult<Value> {
let mut file = None;
let mut style = None;
for arg in args.items() {
match arg {
ast::Arg::Pos(expr) => {
if file.is_none() {
let value = self.eval_semantic_text_expr(expr)?;
if !value.is_empty() {
file = Some(value);
}
}
}
ast::Arg::Named(named) => {
if named.name().get().as_str() == "style" {
let value = self.eval_semantic_text_expr(named.expr())?;
if !value.is_empty() {
style = Some(value);
}
}
}
ast::Arg::Spread(_) => {
return Err(EvalError::argument(
"bibliography does not support spread arguments in MiniEval semantic mode"
.to_string(),
));
}
}
}
let file = file.ok_or_else(|| {
EvalError::argument("bibliography expects a file argument".to_string())
})?;
bibliography_content_value(file, style)
}
/// Evaluate a function call.
fn eval_func_call(&mut self, call: ast::FuncCall) -> EvalResult<Value> {
// Check recursion depth early to prevent stack overflow
self.current_depth += 1;
if self.current_depth > self.config.max_recursion_depth {
self.current_depth -= 1;
return Err(EvalError::new(EvalErrorKind::RecursionLimitExceeded {
max_depth: self.config.max_recursion_depth,
}));
}
let result = self.eval_func_call_inner(call);
self.current_depth -= 1;
result
}
/// Inner implementation of function call evaluation.
fn eval_func_call_inner(&mut self, call: ast::FuncCall) -> EvalResult<Value> {
let callee = call.callee();
let args = call.args();
// Check for field access (method call or module function)
if let ast::Expr::FieldAccess(access) = &callee {
return self.eval_method_call(*access, args);
}
// Get the function name or value
if let ast::Expr::Ident(ident) = &callee {
let name = ident.get().as_str();
// Check if it's a user-defined function
if let Some(Value::Func(closure)) = self.scopes.get(name).cloned() {
return self.call_closure(&closure, args);
}
match name {
"cite" => return self.eval_semantic_cite(args),
"ref" => return self.eval_semantic_ref(args),
"label" => return self.eval_semantic_label(args),
"bibliography" => return self.eval_semantic_bibliography(args),
_ => {}
}
// Try built-in functions
let (pos_args, named_args) = self.eval_args(args)?;
match call_builtin(name, pos_args, named_args, &self.vfs) {
BuiltinResult::Ok(v) => return Ok(v),
BuiltinResult::NotFound => {
// Not a built-in, fall through to raw source
// In compat mode, unknown functions are preserved as ContentNode::FuncCall
if self.config.strict {
return Err(EvalError::undefined(name));
}
}
BuiltinResult::Err(e) => return Err(e),
}
} else {
// Callee is not an identifier - evaluate it to get a function value
// This handles cases like (make-adder(5))(10) or (x(x))(v)
let callee_val = self.eval_expr(callee)?;
if let Value::Func(closure) = callee_val {
return self.call_closure(&closure, args);
}
// If callee evaluated to something else, it's not callable
return Err(EvalError::invalid_op(format!(
"cannot call {} as function",
callee_val.type_name()
)));
}
// Unknown function - evaluate arguments and reconstruct
// This handles Typst functions like table(), grid(), align(), etc.
// that are not implemented in MiniEval but should have their
// arguments evaluated (e.g., dynamic content from map/for loops).
let (pos_args, named_args) = self.eval_args(args)?;
let func_name = match &callee {
ast::Expr::Ident(ident) => ident.get().to_string(),
_ => callee.to_untyped().text().to_string(),
};
Ok(Value::Content(vec![ContentNode::FuncCall {
name: func_name,
args: pos_args
.into_iter()
.map(super::value::Arg::Pos)
.chain(
named_args
.into_iter()
.map(|(k, v)| super::value::Arg::Named(k, v)),
)
.collect(),
}]))
}
/// Evaluate a method call or module function call.
fn eval_method_call(&mut self, access: ast::FieldAccess, args: ast::Args) -> EvalResult<Value> {
let target = access.target();
let field = access.field().get().to_string();
// Check for calc.xxx pattern
if let ast::Expr::Ident(ident) = &target {
if ident.get().as_str() == "calc" {
let (pos_args, _) = self.eval_args(args)?;
return call_calc(&field, pos_args);
}
}
// Evaluate the target
let target_value = self.eval_expr(target)?;
// Evaluate arguments
let (pos_args, _) = self.eval_args(args)?;
// Handle special array methods that need closures
if let Value::Array(ref arr) = target_value {
match field.as_str() {
"map" => return self.array_map(arr.clone(), args),
"filter" => return self.array_filter(arr.clone(), args),
"fold" => return self.array_fold(arr.clone(), args),
"reduce" => return self.array_reduce(arr.clone(), args),
"any" => return self.array_any(arr.clone(), args),
"all" => return self.array_all(arr.clone(), args),
"find" => return self.array_find(arr.clone(), args),
"sorted" if !pos_args.is_empty() => return self.array_sorted_by(arr.clone(), args),
_ => {}
}
}
// Regular method call
call_method(&target_value, &field, pos_args)
}
/// Evaluate function arguments.
///
/// Handles spread arguments for:
/// - `..array` -> extends positional args
/// - `..dict` -> extends named args
/// - `..arguments` -> extends both positional and named args
fn eval_args(&mut self, args: ast::Args) -> EvalResult<(Vec<Value>, IndexMap<String, Value>)> {
let mut pos_args = Vec::new();
let mut named_args = IndexMap::new();
for arg in args.items() {
match arg {
ast::Arg::Pos(expr) => {
pos_args.push(self.eval_expr(expr)?);
}
ast::Arg::Named(named) => {
let key = named.name().get().to_string();
let value = self.eval_expr(named.expr())?;
named_args.insert(key, value);
}
ast::Arg::Spread(spread) => {
let value = self.eval_expr(spread.expr())?;
match value {
Value::Array(arr) => pos_args.extend(arr),
Value::Dict(dict) => named_args.extend(dict),
Value::Arguments(args_val) => {
// Spread Arguments expands both positional and named
pos_args.extend(args_val.positional);
named_args.extend(args_val.named);
}
Value::None => {
// Spreading none is a no-op
}
_ => {
return Err(EvalError::invalid_op(format!(
"cannot spread {} into arguments",
value.type_name()
)));
}
}
}
}
}
Ok((pos_args, named_args))
}
/// Call a user-defined closure.
fn call_closure(&mut self, closure: &Closure, args: ast::Args) -> EvalResult<Value> {
// Note: Recursion depth is already checked by eval_func_call
let (pos_args, named_args) = self.eval_args(args)?;
// Create new scope with captures
self.scopes.enter_with_captures(closure.captures.clone());
// Track which named args are consumed by regular parameters
let mut consumed_named: std::collections::HashSet<&str> = std::collections::HashSet::new();
// Bind regular parameters
let num_regular_params = closure.params.len();
for (i, param) in closure.params.iter().enumerate() {
let value = if let Some(v) = named_args.get(param) {
consumed_named.insert(param.as_str());
v.clone()
} else if i < pos_args.len() {
pos_args[i].clone()
} else if let Some(Some(ref default_source)) = closure.defaults.get(i) {
// Evaluate default in current scope (where prior args are bound)
// This enables `#let f(x, y: x + 1) = ...` style dependent defaults
self.eval_body_source(default_source)?
} else {
Value::None
};
self.scopes.define(param.clone(), value);
}
// Bind sink argument as Arguments (extra positional AND extra named)
if let Some(ref sink_name) = closure.sink {
let extra_pos: Vec<Value> = pos_args.into_iter().skip(num_regular_params).collect();
let extra_named: IndexMap<String, Value> = named_args
.into_iter()
.filter(|(k, _)| !consumed_named.contains(k.as_str()))
.collect();
// Bind as Arguments type, not just Array
self.scopes.define(
sink_name.clone(),
Value::Arguments(Arguments {
positional: extra_pos,
named: extra_named,
}),
);
}
// Parse and evaluate the body
let result = self.eval_body_source(&closure.body_source);
self.scopes.exit();
// Handle return flow
if let Some(FlowEvent::Return(value)) = self.flow.take() {
return Ok(value.unwrap_or(Value::None));
}
result
}
/// Parse and evaluate a body source string.
/// This handles both code expressions (like `x * 2`) and markup (like `[hello]`).
fn eval_body_source(&mut self, source: &str) -> EvalResult<Value> {
// First try parsing as code (for expressions like `x * 2`)
let code_root = parse_code(source);
if code_root.errors().is_empty() {
if let Some(code) = code_root.cast::<ast::Code>() {
return self.eval_code(code);
}
}
// Fall back to parsing as markup
let markup_root = parse(source);
if !markup_root.errors().is_empty() {
return Err(EvalError::syntax(format!(
"failed to parse '{}': {}",
source,
markup_root
.errors()
.iter()
.map(|e| e.message.to_string())
.collect::<Vec<_>>()
.join(", ")
)));
}
if let Some(markup) = markup_root.cast::<ast::Markup>() {
self.eval_markup(markup)
} else {
Err(EvalError::syntax(format!(
"unexpected node type for: {}",
source
)))
}
}
/// Evaluate field access.
fn eval_field_access(&mut self, access: ast::FieldAccess) -> EvalResult<Value> {
let target = self.eval_expr(access.target())?;
let field = access.field().get().as_str();
match target {
Value::Dict(dict) => dict
.get(field)
.cloned()
.ok_or(EvalError::key_not_found(field.to_string())),
Value::Content(_) => {
// Content field access - preserve as raw
let source = access.to_untyped().text().to_string();
Ok(Value::Content(vec![ContentNode::RawSource(source)]))
}
_ => Err(EvalError::invalid_op(format!(
"cannot access field '{}' on {}",
field,
target.type_name()
))),
}
}
// ========================================================================
// Array higher-order methods
// ========================================================================
fn array_map(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
let mut result = Vec::new();
for item in arr {
let value = self.apply_closure(&closure, vec![item])?;
result.push(value);
}
Ok(Value::Array(result))
}
fn array_filter(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
let mut result = Vec::new();
for item in arr {
let keep = self
.apply_closure(&closure, vec![item.clone()])?
.as_bool()?;
if keep {
result.push(item);
}
}
Ok(Value::Array(result))
}
fn array_fold(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let items: Vec<ast::Arg> = args.items().collect();
if items.len() < 2 {
return Err(EvalError::argument(
"fold requires initial value and closure".to_string(),
));
}
let init = if let ast::Arg::Pos(expr) = &items[0] {
self.eval_expr(*expr)?
} else {
return Err(EvalError::argument(
"fold requires positional initial value".to_string(),
));
};
let closure = if let ast::Arg::Pos(expr) = &items[1] {
self.get_closure_from_expr(*expr)?
} else {
return Err(EvalError::argument(
"fold requires closure argument".to_string(),
));
};
let mut acc = init;
for item in arr {
acc = self.apply_closure(&closure, vec![acc, item])?;
}
Ok(acc)
}
fn array_any(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
for item in arr {
let result = self.apply_closure(&closure, vec![item])?.as_bool()?;
if result {
return Ok(Value::Bool(true));
}
}
Ok(Value::Bool(false))
}
fn array_all(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
for item in arr {
let result = self.apply_closure(&closure, vec![item])?.as_bool()?;
if !result {
return Ok(Value::Bool(false));
}
}
Ok(Value::Bool(true))
}
fn array_find(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
for item in arr {
let result = self
.apply_closure(&closure, vec![item.clone()])?
.as_bool()?;
if result {
return Ok(item);
}
}
Ok(Value::None)
}
fn array_reduce(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
if arr.is_empty() {
return Ok(Value::None);
}
let closure = self.get_closure_arg(args)?;
let mut iter = arr.into_iter();
let mut acc = iter.next().unwrap();
for item in iter {
acc = self.apply_closure(&closure, vec![acc, item])?;
}
Ok(acc)
}
fn array_sorted_by(&mut self, arr: Vec<Value>, args: ast::Args) -> EvalResult<Value> {
let closure = self.get_closure_arg(args)?;
// Compute keys for all items
let mut keyed: Vec<(Value, Value)> = Vec::new();
for item in arr {
let key = self.apply_closure(&closure, vec![item.clone()])?;
keyed.push((key, item));
}
// Sort by key
keyed.sort_by(|a, b| match (&a.0, &b.0) {
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::Float(x), Value::Float(y)) => {
x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
}
(Value::Str(x), Value::Str(y)) => x.cmp(y),
_ => std::cmp::Ordering::Equal,
});
let sorted: Vec<Value> = keyed.into_iter().map(|(_, v)| v).collect();
Ok(Value::Array(sorted))
}
/// Get closure from the first argument.
fn get_closure_arg(&mut self, args: ast::Args) -> EvalResult<Closure> {
let first = args
.items()
.next()
.ok_or(EvalError::argument("expected closure argument".to_string()))?;
if let ast::Arg::Pos(expr) = first {
self.get_closure_from_expr(expr)
} else {
Err(EvalError::argument(
"expected positional closure argument".to_string(),
))
}
}
/// Get closure from an expression.
///
/// Supports:
/// - Literal closures: `x => x * 2`
/// - Identifier references: `map(double)` where `double` is defined
/// - Field access: `map(module.func)` or `map(dict.func)`
/// - Builtin functions: `map(str)`, `map(int)`, etc.
fn get_closure_from_expr(&mut self, expr: ast::Expr) -> EvalResult<Closure> {
match expr {
ast::Expr::Closure(c) => {
let value = self.eval_closure(c)?;
if let Value::Func(closure) = value {
Ok((*closure).clone())
} else {
Err(EvalError::type_mismatch("function", value.type_name()))
}
}
ast::Expr::Ident(ident) => {
let name = ident.get().as_str();
// First, try to resolve from scopes (user-defined functions)
if let Some(value) = self.scopes.get(name) {
if let Value::Func(closure) = value {
return Ok((**closure).clone());
} else {
return Err(EvalError::type_mismatch("function", value.type_name()));
}
}
// Second, check if it's a known builtin function and create a wrapper closure
if self.is_builtin_function(name) {
return Ok(self.create_builtin_wrapper(name));
}
// Not found
Err(EvalError::undefined(name))
}
ast::Expr::FieldAccess(access) => {
// Handle module.func or dict.func patterns
let value = self.eval_field_access(access)?;
if let Value::Func(closure) = value {
Ok((*closure).clone())
} else {
Err(EvalError::type_mismatch("function", value.type_name()))
}
}
ast::Expr::Parenthesized(paren) => {
// Handle (func) pattern
self.get_closure_from_expr(paren.expr())
}
_ => Err(EvalError::argument(
"expected closure or function reference",
)),
}
}
/// Check if a name is a known builtin function.
pub fn is_builtin_function(&self, name: &str) -> bool {
matches!(
name,
"str"
| "int"
| "float"
| "bool"
| "type"
| "repr"
| "len"
| "range"
| "array"
| "dict"
| "dictionary"
| "rgb"
| "cmyk"
| "luma"
| "datetime"
| "regex"
| "version"
| "label"
| "lower"
| "upper"
| "lorem"
| "zip"
| "numbering"
| "counter"
| "state"
| "pt"
| "mm"
| "cm"
| "em"
| "panic"
| "assert"
| "measure"
| "layout"
| "place"
| "box"
| "block"
| "grid"
| "stack"
)
}
/// Create a wrapper closure for a builtin function.
/// This allows builtin functions to be passed as arguments to higher-order functions.
fn create_builtin_wrapper(&self, name: &str) -> Closure {
// Create a closure that captures the builtin name and calls it
// The body source is a call expression: `builtin_name(x)`
Closure {
name: Some(format!("<builtin:{}>", name)),
params: vec!["x".to_string()],
body_source: format!("{}(x)", name),
captures: IndexMap::new(),
defaults: vec![None],
sink: None,
}
}
/// Apply a closure to arguments.
fn apply_closure(&mut self, closure: &Closure, args: Vec<Value>) -> EvalResult<Value> {
self.scopes.enter_with_captures(closure.captures.clone());
for (i, param) in closure.params.iter().enumerate() {
let value = args.get(i).cloned().unwrap_or(Value::None);
self.scopes.define(param.clone(), value);
}
let result = self.eval_body_source(&closure.body_source);
self.scopes.exit();
if let Some(FlowEvent::Return(value)) = self.flow.take() {
return Ok(value.unwrap_or(Value::None));
}
result
}
/// Evaluate math content, replacing hash expressions with their values.
///
/// This function traverses a Math AST node and evaluates any embedded
/// hash expressions (like `#n` in `$F_#n$`), returning the expanded math string.
fn eval_math_content(&mut self, node: &SyntaxNode) -> EvalResult<Vec<MathSegment>> {
use SyntaxKind::*;
let mut result = Vec::new();
let children: Vec<_> = node.children().collect();
let mut i = 0;
let push_source = |segments: &mut Vec<MathSegment>, text: &str| {
if text.is_empty() {
return;
}
if let Some(MathSegment::Source(existing)) = segments.last_mut() {
existing.push_str(text);
} else {
segments.push(MathSegment::Source(text.to_string()));
}
};
while i < children.len() {
let child = &children[i];
match child.kind() {
// Hash marks the start of a code expression
Hash => {
// Check for expression after hash
if i + 1 < children.len() {
let expr_node = &children[i + 1];
match expr_node.kind() {
// Simple identifier: #n
Ident => {
let name = expr_node.text().to_string();
if let Some(value) = self.scopes.get(&name) {
result.push(MathSegment::Evaluated(value.clone()));
} else {
push_source(&mut result, &format!("#{}", name));
}
i += 2; // Skip both Hash and Ident
continue;
}
// Parenthesized expression: #(expr)
Parenthesized => {
// Find the inner expression
for inner in expr_node.children() {
if let Some(expr) = inner.cast::<ast::Expr>() {
match self.eval_expr(expr) {
Ok(value) => {
result.push(MathSegment::Evaluated(value));
}
Err(_) => {
push_source(
&mut result,
&format!("#{}", expr_node.text()),
);
}
}
break;
}
}
if !matches!(result.last(), Some(MathSegment::Evaluated(_))) {
// No inner expression found; preserve the original source.
if !expr_node
.children()
.any(|inner| inner.cast::<ast::Expr>().is_some())
{
push_source(&mut result, &format!("#{}", expr_node.text()));
}
}
i += 2; // Skip both Hash and Parenthesized
continue;
}
// Function call: #func(args)
FuncCall => {
if let Some(expr) = expr_node.cast::<ast::Expr>() {
match self.eval_expr(expr) {
Ok(value) => {
result.push(MathSegment::Evaluated(value));
}
Err(_) => {
push_source(
&mut result,
&format!("#{}", expr_node.text()),
);
}
}
} else {
push_source(&mut result, &format!("#{}", expr_node.text()));
}
i += 2;
continue;
}
_ => {
// Unknown expression type after hash, keep as is
push_source(&mut result, "#");
}
}
} else {
// Hash at end with nothing after
push_source(&mut result, "#");
}
}
// Default strategy: if node has children, recurse; otherwise use raw text.
// This ensures we don't miss any container nodes that might contain #expr.
_ => {
if child.children().next().is_some() {
// Container node - recurse to find any nested #expr
result.extend(self.eval_math_content(child)?);
} else {
// Leaf node (no children) - use raw text
push_source(&mut result, child.text().as_str());
}
}
}
i += 1;
}
Ok(result)
}
}
impl Default for MiniEval {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Public API
// ============================================================================
/// Expand macros in Typst source code.
///
/// This function evaluates `#let`, `#for`, `#if`, and function calls,
/// producing expanded source code that can be converted to LaTeX.
///
/// # Example
///
/// ```ignore
/// use tylax::expand_macros;
///
/// let input = r#"
/// #let n = 3
/// #for i in range(n) {
/// Item #(i + 1)
/// }
/// "#;
///
/// let expanded = expand_macros(input)?;
/// // Result: "Item 1\nItem 2\nItem 3\n"
/// ```
/// Result of macro expansion including any warnings generated.
pub struct ExpandResult {
/// The expanded source code
pub output: String,
/// The expanded content nodes before serialization
pub nodes: Vec<ContentNode>,
/// Warnings generated during expansion
pub warnings: Vec<EvalWarning>,
}
/// Expand macros in Typst source code.
///
/// This function evaluates Typst code, expanding macros (`#let`, `#for`, `#if`, etc.)
/// and applying any `#show` rules, then converts the result back to Typst source code.
///
/// Returns both the expanded output and any warnings generated during evaluation.
pub fn expand_macros(source: &str) -> EvalResult<String> {
let result = expand_macros_with_warnings(source)?;
Ok(result.output)
}
/// Normalize whitespace in content nodes.
///
/// This function:
/// 1. Removes consecutive Space nodes (keeps only one)
/// 2. Removes Space nodes before ListItem/EnumItem (they should start at column 0)
///
/// This prevents indentation accumulation in loops like `#for x in arr [- #x]`
fn normalize_content_whitespace(nodes: Vec<ContentNode>) -> Vec<ContentNode> {
let mut result = Vec::with_capacity(nodes.len());
let mut prev_was_space = false;
for node in nodes {
match &node {
ContentNode::Space => {
// Skip consecutive spaces
if !prev_was_space {
result.push(node);
prev_was_space = true;
}
}
ContentNode::ListItem(_) | ContentNode::EnumItem { .. } => {
// Remove space before list items to ensure proper indentation
if prev_was_space && !result.is_empty() {
// Check if last element is Space and remove it
if matches!(result.last(), Some(ContentNode::Space)) {
result.pop();
}
}
result.push(node);
prev_was_space = false;
}
ContentNode::Parbreak => {
// Parbreaks reset space tracking
result.push(node);
prev_was_space = false;
}
_ => {
result.push(node);
prev_was_space = false;
}
}
}
result
}
/// Expand macros in Typst source code, returning warnings as well.
///
/// This is the full version that returns both the expanded output and any warnings.
pub fn expand_macros_with_warnings(source: &str) -> EvalResult<ExpandResult> {
let root = parse(source);
if !root.errors().is_empty() {
return Err(EvalError::syntax(format!(
"parse error: {}",
root.errors()
.iter()
.map(|e| e.message.to_string())
.collect::<Vec<_>>()
.join(", ")
)));
}
let markup = root
.cast::<ast::Markup>()
.ok_or_else(|| EvalError::syntax("expected markup"))?;
let mut eval = MiniEval::new();
let result = eval.eval_markup(markup)?;
// Convert result to content nodes
let nodes = match result {
Value::Content(nodes) => nodes,
Value::None => Vec::new(),
other => vec![ContentNode::Text(other.display())],
};
// Apply show rules to transform content
let transformed_nodes = eval.apply_show_rules(nodes)?;
// Normalize whitespace: remove consecutive Space nodes to prevent
// indentation accumulation in loops (e.g., #for x in arr [- #x])
let normalized_nodes = normalize_content_whitespace(transformed_nodes);
// Convert transformed nodes to string
let output: String = normalized_nodes.iter().map(|n| n.to_typst()).collect();
// Collect warnings
let warnings = eval.take_warnings();
Ok(ExpandResult {
output,
nodes: normalized_nodes,
warnings,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_math_content_preserves_h_func_call_as_structured_segments() {
let result = expand_macros_with_warnings("$a #h(1cm) b$").unwrap();
assert!(
!result.output.contains("[1cm]"),
"structured math output should not regress to h([1cm]), got: {}",
result.output
);
let ContentNode::Math { segments, block } = &result.nodes[0] else {
panic!("expected a math content node, got: {:?}", result.nodes);
};
assert!(!block, "inline math should not be marked as block math");
assert_eq!(
segments.len(),
3,
"unexpected math segments: {:?}",
segments
);
assert_eq!(segments[0], MathSegment::Source("a ".to_string()));
assert_eq!(segments[2], MathSegment::Source(" b".to_string()));
match &segments[1] {
MathSegment::Evaluated(Value::Content(nodes)) => {
assert!(
matches!(
nodes.first(),
Some(ContentNode::FuncCall { name, .. }) if name == "h"
),
"expected the evaluated segment to preserve h(...) as a func call, got: {:?}",
nodes
);
}
other => panic!("expected an evaluated h(...) segment, got: {:?}", other),
}
}
#[test]
fn test_simple_let() {
// Simple variable binding and usage
let result = expand_macros("#let x = 5\n#x").unwrap();
assert!(result.contains("5"), "Expected 5 in: {}", result);
}
#[test]
fn test_for_loop() {
// For loop with content block syntax [...]
let result = expand_macros("#for i in range(3) [\n#i\n]").unwrap();
assert!(result.contains("0"), "Expected 0 in: {}", result);
assert!(result.contains("1"), "Expected 1 in: {}", result);
assert!(result.contains("2"), "Expected 2 in: {}", result);
}
#[test]
fn test_for_loop_list_debug() {
// Debug test to understand the nesting bug
let input = "#for x in (\"A\", \"B\", \"C\") [\n- #x\n]";
let result = expand_macros(input).unwrap();
// Print with visible characters for debugging
eprintln!("Input: {:?}", input);
eprintln!("Result: {:?}", result);
eprintln!("Result bytes: {:?}", result.as_bytes());
// Each list item should start at column 0
for (i, line) in result.lines().enumerate() {
eprintln!(
"Line {}: {:?} (starts with space: {})",
i,
line,
line.starts_with(' ')
);
}
}
#[test]
fn test_conditional() {
// Conditional with content blocks
let result = expand_macros("#if true [yes] else [no]").unwrap();
assert!(result.contains("yes"), "Expected yes in: {}", result);
assert!(!result.contains("no"), "Unexpected no in: {}", result);
}
#[test]
fn test_function_def() {
// Inline closure syntax: (x) => x * 2
let result = expand_macros("#let double = (x) => x * 2\n#double(5)").unwrap();
assert!(result.contains("10"), "Expected 10 in: {}", result);
}
#[test]
fn test_function_def_sugar() {
// Function definition sugar syntax: f(x) = body
let result = expand_macros("#let triple(x) = x * 3\n#triple(4)").unwrap();
assert!(result.contains("12"), "Expected 12 in: {}", result);
}
#[test]
fn test_recursive_function() {
// Recursive function: factorial
let result = expand_macros(
r#"
#let fact(n) = if n <= 1 { 1 } else { n * fact(n - 1) }
#fact(5)
"#,
)
.unwrap();
assert!(result.contains("120"), "Expected 120 in: {}", result);
}
#[test]
fn test_array_join() {
// Array operations - simpler test
let result = expand_macros("#(1, 2, 3).join(\"-\")").unwrap();
assert!(result.contains("1"), "Expected 1 in: {}", result);
assert!(result.contains("2"), "Expected 2 in: {}", result);
assert!(result.contains("3"), "Expected 3 in: {}", result);
}
#[test]
fn test_range() {
// Range function
let result = expand_macros("#range(3).join(\", \")").unwrap();
assert!(result.contains("0"), "Expected 0 in: {}", result);
assert!(result.contains("1"), "Expected 1 in: {}", result);
assert!(result.contains("2"), "Expected 2 in: {}", result);
}
#[test]
fn test_nested_let() {
// Nested let bindings
let result = expand_macros("#let a = 2\n#let b = a * 3\n#b").unwrap();
assert!(result.contains("6"), "Expected 6 in: {}", result);
}
#[test]
fn test_array_len() {
// Array length
let result = expand_macros("#(1, 2, 3, 4, 5).len()").unwrap();
assert!(result.contains("5"), "Expected 5 in: {}", result);
}
// ========================================================================
// Advanced macro tests
// ========================================================================
#[test]
fn test_fibonacci() {
let result = expand_macros(
r#"
#let fib(n) = if n <= 1 { n } else { fib(n - 1) + fib(n - 2) }
#fib(10)
"#,
)
.unwrap();
assert!(
result.contains("55"),
"Expected 55 (fib(10)) in: {}",
result
);
}
#[test]
fn test_closure_capture() {
let result = expand_macros(
r#"
#let make-adder(x) = (y) => x + y
#let add5 = make-adder(5)
#add5(10)
"#,
)
.unwrap();
assert!(result.contains("15"), "Expected 15 in: {}", result);
}
#[test]
fn test_nested_loops() {
let result = expand_macros(
r#"
#for i in range(3) [
#for j in range(3) [(#i,#j)]
]
"#,
)
.unwrap();
assert!(result.contains("(0,0)"), "Expected (0,0) in: {}", result);
assert!(result.contains("(2,2)"), "Expected (2,2) in: {}", result);
}
#[test]
fn test_array_sum() {
let result = expand_macros(r#"#(1, 2, 3, 4, 5).sum()"#).unwrap();
assert!(result.contains("15"), "Expected 15 in: {}", result);
}
#[test]
fn test_string_upper() {
let result = expand_macros(r#"#"hello world".upper()"#).unwrap();
assert!(
result.contains("HELLO WORLD"),
"Expected HELLO WORLD in: {}",
result
);
}
#[test]
fn test_complex_conditional() {
let result = expand_macros(r#"
#let grade(score) = if score >= 90 { "A" } else if score >= 80 { "B" } else if score >= 70 { "C" } else { "F" }
#grade(95), #grade(85), #grade(50)
"#).unwrap();
assert!(result.contains("A"), "Expected A in: {}", result);
assert!(result.contains("B"), "Expected B in: {}", result);
assert!(result.contains("F"), "Expected F in: {}", result);
}
#[test]
fn test_function_composition() {
let result = expand_macros(
r#"
#let compose(f, g) = (x) => f(g(x))
#let double(x) = x * 2
#let inc(x) = x + 1
#let f = compose(inc, double)
#f(5)
"#,
)
.unwrap();
// double(5) = 10, then inc(10) = 11
assert!(result.contains("11"), "Expected 11 in: {}", result);
}
#[test]
fn test_map_with_closure_variable() {
// Test passing a closure variable to map
let result = expand_macros(
r#"
#let make_adder(k) = (x) => x + k
#let add3 = make_adder(3)
#let xs = (1, 2, 3)
#xs.map(add3).join(", ")
"#,
)
.unwrap();
// 1+3=4, 2+3=5, 3+3=6
assert!(
result.contains("4") && result.contains("5") && result.contains("6"),
"Expected 4, 5, 6 in: {}",
result
);
}
#[test]
fn test_is_builtin_function() {
let eval = MiniEval::new();
assert!(eval.is_builtin_function("str"), "str should be a builtin");
assert!(eval.is_builtin_function("int"), "int should be a builtin");
assert!(
eval.is_builtin_function("range"),
"range should be a builtin"
);
assert!(
!eval.is_builtin_function("foo"),
"foo should not be a builtin"
);
}
#[test]
fn test_str_builtin_direct_call() {
// Test that str() works when called directly
let result = expand_macros(r#"#str(42)"#).unwrap();
assert!(
result.contains("42"),
"str(42) should produce '42' in: {}",
result
);
}
#[test]
fn test_str_in_closure() {
// Test that str() works when called inside a closure body
let result = expand_macros(
r#"
#let wrap(f, v) = f(v)
#wrap(str, 123)
"#,
)
.unwrap();
assert!(
result.contains("123"),
"wrap(str, 123) should produce '123' in: {}",
result
);
}
#[test]
fn test_lazy_defaults() {
// Test that default arguments can depend on prior parameters
// Note: For now, simpler test - dependent defaults are a stretch goal
let result = expand_macros(
r#"
#let f(x, y: 10) = (x, y)
#f(5)
"#,
)
.unwrap();
// f(5) -> x=5, y=10
assert!(
result.contains("5") && result.contains("10"),
"Expected (5, 10) in: {}",
result
);
}
#[test]
fn test_lazy_defaults_dependent() {
// Test that default arguments can depend on prior parameters
let result = expand_macros(
r#"
#let f(x, y: x + 1) = (x, y)
#f(5)
"#,
)
.unwrap();
// f(5) -> x=5, y=5+1=6
assert!(
result.contains("5") && result.contains("6"),
"Expected (5, 6) in: {}",
result
);
}
#[test]
fn test_content_introspection() {
// Test content.func() and content.text()
let result = expand_macros(
r#"
#let h = [= Hello World]
#h.first().func()
"#,
)
.unwrap();
// The heading's func should be "heading"
assert!(
result.contains("heading"),
"Expected 'heading' in: {}",
result
);
}
#[test]
fn test_map_with_builtin_str() {
// Test passing builtin str function to map
let result = expand_macros(
r#"
#let nums = (1, 2, 3)
#nums.map(str).join("-")
"#,
)
.unwrap();
assert!(result.contains("1-2-3"), "Expected 1-2-3 in: {}", result);
}
#[test]
fn test_chained_map() {
// Test chaining map operations
let result = expand_macros(
r#"
#let double = (x) => x * 2
#(1, 2, 3).map(double).map(str).join(", ")
"#,
)
.unwrap();
// 1*2=2, 2*2=4, 3*2=6
assert!(
result.contains("2") && result.contains("4") && result.contains("6"),
"Expected 2, 4, 6 in: {}",
result
);
}
#[test]
fn test_accumulator_loop() {
let result = expand_macros(
r#"
#let sum-list(arr) = {
let acc = 0
for x in arr {
acc = acc + x
}
acc
}
#sum-list((1, 2, 3, 4, 5))
"#,
)
.unwrap();
assert!(result.contains("15"), "Expected 15 in: {}", result);
}
#[test]
fn test_generate_sequence() {
// Generate a sequence with loop
let result = expand_macros(
r#"
#for i in range(1, 4) [#(i * 3), ]
"#,
)
.unwrap();
assert!(result.contains("3"), "Expected 3 in: {}", result);
assert!(result.contains("6"), "Expected 6 in: {}", result);
assert!(result.contains("9"), "Expected 9 in: {}", result);
}
#[test]
fn test_string_split_join() {
let result = expand_macros(r#"#"a,b,c".split(",").join(" | ")"#).unwrap();
assert!(
result.contains("a | b | c"),
"Expected 'a | b | c' in: {}",
result
);
}
#[test]
fn test_calc_functions() {
let result = expand_macros(r#"#calc.abs(-5)"#).unwrap();
assert!(result.contains("5"), "Expected 5 in: {}", result);
let result2 = expand_macros(r#"#calc.max(1, 5, 3)"#).unwrap();
assert!(result2.contains("5"), "Expected 5 in: {}", result2);
let result3 = expand_macros(r#"#calc.min(1, 5, 3)"#).unwrap();
assert!(result3.contains("1"), "Expected 1 in: {}", result3);
}
#[test]
fn test_array_filter_pattern() {
// Manual filter implementation
let result = expand_macros(
r#"
#let filter-even(arr) = {
let result = ()
for x in arr {
if calc.rem(x, 2) == 0 {
result = result + (x,)
}
}
result
}
#filter-even((1, 2, 3, 4, 5, 6)).join(", ")
"#,
)
.unwrap();
assert!(result.contains("2"), "Expected 2 in: {}", result);
assert!(result.contains("4"), "Expected 4 in: {}", result);
assert!(result.contains("6"), "Expected 6 in: {}", result);
assert!(!result.contains("1,"), "Unexpected 1 in: {}", result);
}
#[test]
fn test_power_function() {
let result = expand_macros(
r#"
#let pow(base, exp) = if exp == 0 { 1 } else { base * pow(base, exp - 1) }
#pow(2, 10)
"#,
)
.unwrap();
assert!(
result.contains("1024"),
"Expected 1024 (2^10) in: {}",
result
);
}
#[test]
fn test_gcd() {
let result = expand_macros(
r#"
#let gcd(a, b) = if b == 0 { a } else { gcd(b, calc.rem(a, b)) }
#gcd(48, 18)
"#,
)
.unwrap();
assert!(
result.contains("6"),
"Expected 6 (gcd of 48,18) in: {}",
result
);
}
#[test]
fn test_demo_output() {
// Quick demonstration of what expand_macros produces
let tests = vec![
(
"fib",
r#"
#let fib(n) = if n <= 1 { n } else { fib(n - 1) + fib(n - 2) }
#for i in range(8) [F#i=#fib(i) ]
"#,
),
(
"closure",
r#"
#let make-adder(x) = (y) => x + y
#let add5 = make-adder(5)
add5(3)=#add5(3)
"#,
),
(
"custom map",
r#"
#let my-map(arr, f) = {
let result = ()
for item in arr {
result = result + (f(item),)
}
result
}
#my-map((1, 2, 3), x => x * x).join(", ")
"#,
),
(
"GCD",
r#"
#let gcd(a, b) = if b == 0 { a } else { gcd(b, calc.rem(a, b)) }
gcd(48,18)=#gcd(48, 18)
"#,
),
(
"tail recursion",
r#"
#let sum-to(n) = {
let helper(i, acc) = if i > n { acc } else { helper(i + 1, acc + i) }
helper(1, 0)
}
sum(1..10)=#sum-to(10)
"#,
),
];
for (name, code) in tests {
let result = expand_macros(code).unwrap();
eprintln!("=== {} ===", name);
eprintln!("{}", result.trim());
eprintln!();
}
}
#[test]
fn test_ackermann() {
let code = r#"
#let ack(m, n) = if m == 0 { n + 1 } else if n == 0 { ack(m - 1, 1) } else { ack(m - 1, ack(m, n - 1)) }
#ack(3, 2)
"#;
let result = expand_macros(code).unwrap();
assert!(result.contains("29"), "Ackermann failed: {}", result);
}
#[test]
fn test_mutual_recursion() {
let code = r#"
#let is-even(n) = if n == 0 { true } else { is-odd(n - 1) }
#let is-odd(n) = if n == 0 { false } else { is-even(n - 1) }
#is-even(10)
#is-even(11)
"#;
let result = expand_macros(code).unwrap();
assert!(result.contains("true"), "10 should be even");
assert!(result.contains("false"), "11 should not be even");
}
#[test]
fn test_quicksort() {
let code = r#"
#let filter(arr, f) = {
let res = ()
for x in arr { if f(x) { res = res + (x,) } }
res
}
#let quicksort(arr) = {
if arr.len() <= 1 { arr } else {
let pivot = arr.first()
let rest = arr.slice(1)
let less = filter(rest, x => x <= pivot)
let greater = filter(rest, x => x > pivot)
quicksort(less) + (pivot,) + quicksort(greater)
}
}
#quicksort((3, 1, 4, 1, 5, 9, 2, 6)).join(",")
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("1,1,2,3,4,5,6,9"),
"Quicksort failed: {}",
result
);
}
#[test]
fn test_matmul() {
let code = r#"
#let mat-mul(A, B) = {
let m = A.len()
let n = A.at(0).len()
let p = B.at(0).len()
let C = ()
for i in range(m) {
let row = ()
for j in range(p) {
let sum = 0
for k in range(n) {
sum = sum + A.at(i).at(k) * B.at(k).at(j)
}
row = row + (sum,)
}
C = C + (row,)
}
C
}
#let A = ((1, 2), (3, 4))
#let B = ((2, 0), (1, 2))
#mat-mul(A, B)
"#;
let result = expand_macros(code).unwrap();
assert!(result.contains("4"), "MatMul missing 4");
assert!(result.contains("10"), "MatMul missing 10");
assert!(result.contains("8"), "MatMul missing 8");
}
#[test]
fn test_z_combinator_simple() {
// Simpler Z-combinator test: countdown without multiplication
let code = r#"
#let Z(f) = {
let inner(x) = {
let g(v) = (x(x))(v)
f(g)
}
inner(inner)
}
#let countdown = Z(f => n => if n <= 0 { "done" } else { f(n - 1) })
#countdown(3)
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("done"),
"Z Combinator countdown failed: {}",
result
);
}
#[test]
fn test_z_combinator_factorial() {
// Full Z-combinator with factorial
let code = r#"
#let Z(f) = {
let inner(x) = {
let g(v) = (x(x))(v)
f(g)
}
inner(inner)
}
#let fact = Z(f => n => if n <= 1 { 1 } else { n * f(n - 1) })
#fact(5)
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("120"),
"Z Combinator factorial failed: {}",
result
);
}
#[test]
fn test_block_returns_int() {
// Verify code blocks return the correct type
let code = r#"
#let x = { 1 }
#type(x)
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("int"),
"Block should return int: {}",
result
);
}
#[test]
fn test_if_returns_int() {
// Verify if expressions return correct type
let code = r#"
#let x = if true { 1 } else { 2 }
#type(x)
"#;
let result = expand_macros(code).unwrap();
assert!(result.contains("int"), "If should return int: {}", result);
}
#[test]
fn test_nested_func_call() {
// Test nested function calls like (f(x))(y)
let code = r#"
#let make-adder(x) = (y) => x + y
#let add3 = make-adder(3)
#(make-adder(5))(10)
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("15"),
"Nested call should return 15: {}",
result
);
}
// ========================================================================
// Control flow tests
// ========================================================================
#[test]
fn test_break_in_nested_loops() {
// break should only exit the innermost loop
let code = r#"
#for i in range(3) {
for j in range(3) {
if j == 1 { break }
[j=#j]
}
[i=#i]
}
"#;
let result = expand_macros(code).unwrap();
// Each outer loop iteration should only output j=0 (break at j=1)
// Then continue with i=0, i=1, i=2
assert!(result.contains("j=0"), "Should have j=0 in: {}", result);
assert!(
!result.contains("j=1"),
"Should NOT have j=1 in: {}",
result
);
assert!(
!result.contains("j=2"),
"Should NOT have j=2 in: {}",
result
);
// Outer loop should complete all iterations
assert!(result.contains("i=0"), "Should have i=0 in: {}", result);
assert!(result.contains("i=1"), "Should have i=1 in: {}", result);
assert!(result.contains("i=2"), "Should have i=2 in: {}", result);
}
#[test]
fn test_return_in_function() {
// return should exit the function with a value
let code = r#"
#let f() = {
for i in range(10) {
if i == 3 { return i }
}
999
}
#f()
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("3"),
"Should return 3 from function: {}",
result
);
assert!(
!result.contains("999"),
"Should NOT reach 999 in: {}",
result
);
}
#[test]
fn test_continue_in_loop() {
// continue should skip to next iteration
// Use content block syntax [...] for output
let code = r#"#for i in range(5) [
#if calc.rem(i, 2) == 0 { continue }
#i
]"#;
let result = expand_macros(code).unwrap();
// Should only output odd numbers: 1, 3
assert!(result.contains("1"), "Should have 1 in: {}", result);
assert!(result.contains("3"), "Should have 3 in: {}", result);
// Note: 0, 2, 4 might appear in whitespace/formatting, so we check more carefully
}
#[test]
fn test_while_with_break() {
// break in while loop - test by counting iterations
let code = r#"
#let test-while() = {
let count = 0
let i = 0
while i < 10 {
if i == 3 { break }
count = count + 1
i = i + 1
}
count
}
#test-while()
"#;
let result = expand_macros(code).unwrap();
// Should count 3 iterations (0, 1, 2) then break at i=3
assert!(result.contains("3"), "Should have count=3 in: {}", result);
}
// ========================================================================
// Graceful degradation tests (compat mode)
// ========================================================================
#[test]
fn test_unknown_function_compat_mode() {
// Unknown functions should NOT cause a panic in compat mode
// They should be preserved as function calls
let code = r#"#some_totally_unknown_func(1, 2, "test")"#;
let result = expand_macros(code);
// In compat mode, this should succeed (not panic)
assert!(
result.is_ok(),
"Unknown function should not panic in compat mode"
);
}
#[test]
fn test_unknown_method_error() {
// Unknown methods should return an error (not panic)
let code = r#"#(1, 2, 3).some_unknown_method()"#;
let result = expand_macros(code);
// This should fail with an error, not panic
assert!(result.is_err(), "Unknown method should return error");
}
// ========================================================================
// Plan-specified edge case tests (from audit plan)
// ========================================================================
#[test]
fn test_plan_basic_shadowing() {
// Plan case: #let x = 1; #{ let x = 2; x } #x -> 2, 1
let code = r#"
#let x = 1
#{ let x = 2; x }
#x
"#;
let result = expand_macros(code).unwrap();
// Inner block should have 2, outer should have 1
assert!(result.contains("2"), "Inner x should be 2 in: {}", result);
assert!(result.contains("1"), "Outer x should be 1 in: {}", result);
}
#[test]
fn test_plan_closure_captures_value() {
// Plan case: Closure should capture value, not reference
// #let make_adder(n) = (x) => x + n
// #let add5 = make_adder(5)
// #add5(10) -> 15
let code = r#"
#let make_adder(n) = (x) => x + n
#let add5 = make_adder(5)
#add5(10)
"#;
let result = expand_macros(code).unwrap();
assert!(
result.contains("15"),
"add5(10) should be 15 in: {}",
result
);
}
#[test]
fn test_plan_closure_capture_in_loop() {
// Plan case: Classic closure capture trap
// Each closure in the loop should capture a different value
// This tests that capture_all() clones values correctly
let code = r#"
#let funcs = ()
#for i in range(3) {
funcs = funcs + ((() => i),)
}
// Call each function and collect results
#let results = funcs.map(f => f())
#results
"#;
let result = expand_macros(code).unwrap();
// In Typst (and our MiniEval), each closure captures the value at definition time
// So we should see 0, 1, 2 (not 2, 2, 2 like in some languages with late binding)
assert!(
result.contains("0"),
"First closure should capture 0: {}",
result
);
assert!(
result.contains("1"),
"Second closure should capture 1: {}",
result
);
assert!(
result.contains("2"),
"Third closure should capture 2: {}",
result
);
}
#[test]
fn test_plan_nested_break_only_inner() {
// Plan case: break in nested loops should only exit inner loop
let code = r#"
#let results = ()
#for i in range(3) {
for j in range(3) {
if j == 1 { break }
results = results + ((i, j),)
}
}
#results
"#;
let result = expand_macros(code).unwrap();
// Each outer loop should only produce j=0, then break
// So we expect (0,0), (1,0), (2,0)
assert!(
result.contains("0") && result.contains("1") && result.contains("2"),
"Should have all i values: {}",
result
);
}
#[test]
fn test_plan_return_in_nested_loop() {
// Plan case: return should exit function, not just loop
let code = r#"
#let f() = {
for i in range(10) {
if i == 3 { return i }
}
999
}
#f()
"#;
let result = expand_macros(code).unwrap();
assert!(result.contains("3"), "Should return 3: {}", result);
assert!(!result.contains("999"), "Should not reach 999: {}", result);
}
#[test]
fn test_plan_continue_skips_iteration() {
// Plan case: continue should skip to next iteration
let code = r#"
#let results = ()
#for i in range(5) {
if calc.rem(i, 2) == 0 { continue }
results = results + (i,)
}
#results
"#;
let result = expand_macros(code).unwrap();
// Should only have odd numbers: 1, 3
assert!(result.contains("1"), "Should have 1: {}", result);
assert!(result.contains("3"), "Should have 3: {}", result);
}
}