1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
//! Scheme evaluator (eval loop)
//!
//! Ported from OpenJade's `Interpreter.cxx` (~2,000 lines).
//!
//! ## Core Responsibilities
//!
//! 1. **Evaluate expressions** - Transform Values into results
//! 2. **Special forms** - Handle if, let, define, lambda, quote, etc.
//! 3. **Function application** - Call procedures with arguments
//! 4. **Tail call optimization** - Prevent stack overflow in recursive functions
//!
//! ## OpenJade Correspondence
//!
//! | Dazzle | OpenJade | Purpose |
//! |-----------------|---------------------------|----------------------------|
//! | `Evaluator` | `Interpreter` | Main evaluator state |
//! | `eval()` | `Interpreter::eval()` | Core eval loop |
//! | `apply()` | `Interpreter::apply()` | Function application |
//! | `eval_special()`| `Interpreter::evalXXX()` | Special form handlers |
//!
//! ## Evaluation Rules (R4RS)
//!
//! - **Self-evaluating**: Numbers, strings, booleans, characters → return as-is
//! - **Symbols**: Look up in environment
//! - **Lists**: First element determines behavior:
//! - Special form keyword → handle specially
//! - Otherwise → evaluate all elements, apply first to rest
use crate::scheme::environment::Environment;
use crate::scheme::parser::Position;
use crate::scheme::value::{Procedure, Value};
use crate::scheme::arena::{Arena, ValueId, ValueData};
use crate::scheme::vm::VM;
use crate::scheme::compiler::Compiler;
use crate::scheme::instruction::Instruction;
use crate::scheme::bridge::{value_to_arena, arena_to_value};
use crate::grove::{Grove, Node};
use crate::fot::FotBuilder;
use gc::Gc;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
// Thread-local evaluator context for primitives
//
// Similar to OpenJade's approach, we use thread-local storage to give
// primitives access to the evaluator state (current node, grove, etc.)
// without changing all primitive signatures.
//
// This is safe because:
// 1. Scheme evaluation is single-threaded in our implementation
// 2. The context is set/cleared around each eval call
// 3. Primitives only run during evaluation
thread_local! {
static EVALUATOR_CONTEXT: RefCell<Option<EvaluatorContext>> = RefCell::new(None);
}
/// Context available to primitives during evaluation
#[derive(Clone)]
pub struct EvaluatorContext {
pub grove: Option<Rc<dyn Grove>>,
pub current_node: Option<Rc<Box<dyn Node>>>,
pub backend: Option<Rc<RefCell<dyn FotBuilder>>>,
}
/// Get the current evaluator context (for use in primitives)
pub fn get_evaluator_context() -> Option<EvaluatorContext> {
EVALUATOR_CONTEXT.with(|ctx| ctx.borrow().clone())
}
/// Check if evaluator context is currently set
fn has_evaluator_context() -> bool {
EVALUATOR_CONTEXT.with(|ctx| ctx.borrow().is_some())
}
/// Set the evaluator context (called by evaluator before eval)
fn set_evaluator_context(ctx: EvaluatorContext) {
EVALUATOR_CONTEXT.with(|c| *c.borrow_mut() = Some(ctx));
}
/// Clear the evaluator context (called by evaluator after eval)
fn clear_evaluator_context() {
EVALUATOR_CONTEXT.with(|c| *c.borrow_mut() = None);
}
// =============================================================================
// Call Stack (for error reporting)
// =============================================================================
use crate::scheme::value::SourceInfo;
/// A call stack frame
///
/// Tracks function calls for error reporting with source locations.
#[derive(Debug, Clone)]
pub struct CallFrame {
/// Function name (or "<lambda>" for anonymous functions)
pub function_name: String,
/// Source location (file:line:column)
pub source: Option<SourceInfo>,
}
impl CallFrame {
pub fn new(function_name: String, source: Option<SourceInfo>) -> Self {
CallFrame {
function_name,
source,
}
}
}
// =============================================================================
// Evaluation Error
// =============================================================================
/// Evaluation error with call stack
#[derive(Debug, Clone)]
pub struct EvalError {
pub message: String,
pub call_stack: Vec<CallFrame>,
}
impl EvalError {
pub fn new(message: String) -> Self {
EvalError {
message,
call_stack: Vec::new(),
}
}
/// Create error with call stack
pub fn with_stack(message: String, call_stack: Vec<CallFrame>) -> Self {
EvalError {
message,
call_stack,
}
}
}
impl std::fmt::Display for EvalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// OpenJade-style format: file:line:col:E: message
write!(f, "{}", self.message)?;
// Show call stack in reverse order (innermost to outermost, matching OpenJade)
for (i, frame) in self.call_stack.iter().rev().enumerate() {
if let Some(ref source) = frame.source {
// First frame gets a newline before it, rest don't
if i == 0 {
writeln!(f, "\n{}:{}:{}:I: called from here",
source.file, source.pos.line, source.pos.column)?;
} else {
writeln!(f, "{}:{}:{}:I: called from here",
source.file, source.pos.line, source.pos.column)?;
}
} else {
if i == 0 {
writeln!(f, "\n{}:I: called from here", frame.function_name)?;
} else {
writeln!(f, "{}:I: called from here", frame.function_name)?;
}
}
}
Ok(())
}
}
impl std::error::Error for EvalError {}
pub type EvalResult = Result<Value, EvalError>;
// =============================================================================
// DSSSL Processing Mode (OpenJade ProcessingMode.h/ProcessingMode.cxx)
// =============================================================================
/// Construction rule for DSSSL processing
///
/// Corresponds to OpenJade's `ElementRule` + `Rule` + `Action`.
/// Stores the pattern (element name) and action (expression to evaluate).
#[derive(Clone)]
pub struct ConstructionRule {
/// Element name pattern (GI) - the actual element being matched
pub element_name: String,
/// Context pattern - parent element names (empty for simple patterns)
/// For `(part title)`, this would be vec!["part"]
/// For simple `title`, this would be empty
pub context: Vec<String>,
/// Construction expression (returns sosofo when evaluated)
pub expr: Value,
/// Source position where this rule was defined (for error reporting)
pub source_file: Option<String>,
pub source_pos: Option<Position>,
/// Cached bytecode instructions (OpenJade's InsnPtr optimization)
///
/// When VM is enabled, we compile the expression once and cache the instructions.
/// This is the key optimization that makes OpenJade fast: compile once, run many times.
///
/// Tuple: (instructions, start_ip)
pub cached_instructions: RefCell<Option<(Vec<Instruction>, usize)>>,
}
/// Processing mode containing construction rules
///
/// Corresponds to OpenJade's `ProcessingMode` class.
/// Stores all element construction rules defined in the template.
pub struct ProcessingMode {
/// Construction rules indexed by element name for O(1) lookup
/// HashMap<element_name, Vec<rules_for_that_element>>
/// This avoids linear search through all rules for every element.
pub rules: std::collections::HashMap<String, Vec<ConstructionRule>>,
/// Default construction rule (fallback when no specific rule matches)
pub default_rule: Option<Value>,
}
impl ProcessingMode {
/// Create a new empty processing mode
pub fn new() -> Self {
ProcessingMode {
rules: std::collections::HashMap::new(),
default_rule: None,
}
}
/// Add a construction rule
pub fn add_rule(&mut self, element_name: String, context: Vec<String>, expr: Value, source_file: Option<String>, source_pos: Option<Position>) {
// Insert rule into HashMap, grouped by element name
self.rules
.entry(element_name.clone())
.or_insert_with(Vec::new)
.push(ConstructionRule {
element_name,
context,
expr,
source_file,
source_pos,
cached_instructions: RefCell::new(None),
});
}
/// Add a default construction rule
pub fn add_default_rule(&mut self, expr: Value) {
self.default_rule = Some(expr);
}
/// Find matching rule for an element
///
/// Corresponds to OpenJade's `ProcessingMode::findMatch()`.
/// Returns the first rule matching the given element name and context.
///
/// OPTIMIZATION: Uses HashMap lookup by element name (O(1)) instead of
/// linear search through all rules (O(N)). Critical for large documents!
pub fn find_match(&self, gi: &str, node: &dyn crate::grove::Node) -> Option<&ConstructionRule> {
// Fast path: lookup rules for this specific element name
let rules_for_element = self.rules.get(gi)?;
// Now search only among rules for this element (typically 1-5 rules)
rules_for_element.iter().find(|rule| {
// Element name already matches (we looked it up by GI)
// If rule has no context, it matches any parent
if rule.context.is_empty() {
return true;
}
// Check if parent chain matches the context
let mut current = node.parent();
for expected_parent in rule.context.iter().rev() {
match current {
Some(ref parent_node) => {
if let Some(parent_gi) = parent_node.gi() {
if parent_gi != *expected_parent {
return false;
}
current = parent_node.parent();
} else {
return false;
}
}
None => return false,
}
}
true
})
}
}
/// Manager for multiple processing modes
///
/// DSSSL supports multiple named modes for different processing contexts.
/// The unnamed mode (empty string key) is the initial/default mode.
pub struct ModeManager {
/// Map of mode name to processing mode
modes: std::collections::HashMap<String, ProcessingMode>,
}
impl ModeManager {
/// Create a new mode manager with an empty default mode
pub fn new() -> Self {
let mut modes = std::collections::HashMap::new();
modes.insert(String::new(), ProcessingMode::new());
ModeManager { modes }
}
/// Get or create a mode by name
pub fn get_or_create_mode(&mut self, name: &str) -> &mut ProcessingMode {
self.modes.entry(name.to_string()).or_insert_with(ProcessingMode::new)
}
/// Get a mode by name (read-only)
pub fn get_mode(&self, name: &str) -> Option<&ProcessingMode> {
self.modes.get(name)
}
/// Get the default (unnamed) mode
pub fn default_mode(&mut self) -> &mut ProcessingMode {
self.get_or_create_mode("")
}
/// Get the default (unnamed) mode (read-only)
pub fn get_default_mode(&self) -> Option<&ProcessingMode> {
self.get_mode("")
}
}
// =============================================================================
// Evaluator
// =============================================================================
/// Scheme evaluator
///
/// Corresponds to OpenJade's `Interpreter` class.
///
/// ## Usage
///
/// ```ignore
/// let mut evaluator = Evaluator::new();
/// let result = evaluator.eval(expr, env)?;
/// ```
pub struct Evaluator {
/// Arena for arena-based values (Phase 2 migration)
///
/// Used for hot primitives (car, cdr, cons, null?, equal?) to eliminate Gc overhead.
/// During Phase 2, this works in dual-mode: Values are converted to ValueIds for hot
/// primitives, then converted back.
arena: Arena,
/// Manager for multiple processing modes
///
/// Corresponds to OpenJade's mode management.
/// DSSSL supports multiple named modes for different processing contexts.
mode_manager: ModeManager,
/// Current mode name for rule definition
///
/// When defining rules with `(element ...)` or `(default ...)`, they go into this mode.
/// Empty string means the unnamed/default mode.
/// Set by `(mode name ...)` special form.
current_mode: String,
/// Current processing mode for rule lookup
///
/// When processing nodes with `process-children`, rules are looked up in this mode.
/// Empty string means the unnamed/default mode.
/// Set by `(with-mode name ...)` special form.
current_processing_mode: String,
/// Backend for output generation (FotBuilder)
///
/// This is used by the `make` special form to write flow objects to output.
/// Wrapped in Rc<RefCell<>> to allow shared mutable access.
backend: Option<Rc<RefCell<dyn FotBuilder>>>,
/// Call stack for error reporting
///
/// Tracks function calls with their source locations.
/// Used to generate helpful error messages with clickable file paths.
call_stack: Vec<CallFrame>,
/// Current source file being evaluated (for error reporting)
///
/// Set when loading templates, used to provide context in errors.
current_source_file: Option<String>,
/// Current position in source (for error reporting)
///
/// Tracks line and column for the expression being evaluated.
current_position: Option<Position>,
/// Line mappings for translating output lines to source files
///
/// When templates are loaded from XML wrappers that concatenate multiple files,
/// this maps output line numbers to (source_file, source_line) pairs.
/// Used to provide accurate file names and line numbers in error messages.
line_mappings: Vec<LineMapping>,
/// Enable VM-based execution (OpenJade's bytecode model)
///
/// When true, expressions are compiled to bytecode and executed with the VM.
/// When false, uses tree-walking interpreter (slower but simpler).
/// This flag allows benchmarking VM vs tree-walker performance.
use_vm: bool,
/// Instruction cache for lambda expressions
///
/// Maps lambda Value pointers to cached (instructions, start_ip).
/// This enables "compile once, run many" for frequently-called lambdas.
lambda_cache: HashMap<usize, (Vec<Instruction>, usize)>,
/// VM global variables (name -> ValueId)
///
/// When use_vm is true, this HashMap persists global variables across evaluations.
/// Each VM execution saves its globals here and restores them on next execution.
vm_globals: HashMap<String, ValueId>,
/// Counter for processed nodes (for periodic GC)
///
/// Tracks how many nodes have been processed. Used to trigger garbage collection
/// periodically to prevent memory accumulation during long-running document processing.
nodes_processed: usize,
}
/// Line mapping entry - maps a line number in concatenated code to its source file and line
#[derive(Debug, Clone)]
pub struct LineMapping {
/// Line number in the concatenated output (1-indexed)
pub output_line: usize,
/// Source file path
pub source_file: String,
/// Line number in the source file (1-indexed)
pub source_line: usize,
}
impl Evaluator {
/// Create a new evaluator without a grove
pub fn new() -> Self {
Evaluator {
arena: Arena::new(),
mode_manager: ModeManager::new(),
current_mode: String::new(), // Start with unnamed/default mode
current_processing_mode: String::new(), // Start with unnamed/default mode
backend: None,
call_stack: Vec::new(),
current_source_file: None,
current_position: None,
line_mappings: Vec::new(),
use_vm: std::env::var("DAZZLE_VM").is_ok(), // Enable VM via environment variable
lambda_cache: HashMap::new(),
vm_globals: HashMap::new(), // Persists VM globals across evaluations
nodes_processed: 0,
}
}
/// Create a new evaluator with a grove
pub fn with_grove(grove: Rc<dyn Grove>) -> Self {
let mut arena = Arena::new();
arena.grove = Some(grove);
Evaluator {
arena,
mode_manager: ModeManager::new(),
current_mode: String::new(), // Start with unnamed/default mode
current_processing_mode: String::new(), // Start with unnamed/default mode
backend: None,
call_stack: Vec::new(),
current_source_file: None,
current_position: None,
line_mappings: Vec::new(),
use_vm: std::env::var("DAZZLE_VM").is_ok(), // Enable VM via environment variable
lambda_cache: HashMap::new(),
vm_globals: HashMap::new(), // Persists VM globals across evaluations
nodes_processed: 0,
}
}
/// Enable VM-based execution (for benchmarking)
pub fn enable_vm(&mut self) {
self.use_vm = true;
}
/// Disable VM-based execution (use tree-walker)
pub fn disable_vm(&mut self) {
self.use_vm = false;
}
/// Set line mappings for error reporting
pub fn set_line_mappings(&mut self, mappings: Vec<LineMapping>) {
self.line_mappings = mappings;
}
/// Set the current source file (for error reporting)
pub fn set_source_file(&mut self, file: String) {
self.current_source_file = Some(file);
}
/// Get the current source file
pub fn source_file(&self) -> Option<&str> {
self.current_source_file.as_deref()
}
/// Set the current position (for error reporting)
pub fn set_position(&mut self, position: Position) {
self.current_position = Some(position);
}
/// Push a call frame onto the stack
fn push_call_frame(&mut self, function_name: String, source: Option<SourceInfo>) {
self.call_stack.push(CallFrame::new(function_name, source));
}
/// Pop a call frame from the stack
fn pop_call_frame(&mut self) {
self.call_stack.pop();
}
/// Create an error with the current call stack and position
fn error_with_stack(&self, message: String) -> EvalError {
// Include current position in the error message (OpenJade format)
let full_message = match (&self.current_source_file, &self.current_position) {
(Some(file), Some(pos)) => {
format!("{}:{}:{}:E: {}", file, pos.line, pos.column, message)
}
(Some(file), None) => {
format!("{}:E: {}", file, message)
}
_ => message,
};
EvalError::with_stack(full_message, self.call_stack.clone())
}
/// Set the backend
pub fn set_backend(&mut self, backend: Rc<RefCell<dyn FotBuilder>>) {
self.backend = Some(backend);
}
/// Set the grove
pub fn set_grove(&mut self, grove: Rc<dyn Grove>) {
self.arena.grove = Some(grove);
}
/// Get the grove
pub fn grove(&self) -> Option<&Rc<dyn Grove>> {
self.arena.grove.as_ref()
}
/// Get static string name for a known primitive
///
/// Returns a `'static str` for the primitive name if it's known,
/// allowing it to be stored in a Procedure::Primitive value.
fn get_primitive_static_name(&self, name: &str) -> Option<&'static str> {
match name {
// R4RS list primitives
"cons" => Some("cons"),
"car" => Some("car"),
"cdr" => Some("cdr"),
"cadr" => Some("cadr"),
"caddr" => Some("caddr"),
"cadddr" => Some("cadddr"),
"list" => Some("list"),
"length" => Some("length"),
"append" => Some("append"),
"reverse" => Some("reverse"),
"list-ref" => Some("list-ref"),
"list-tail" => Some("list-tail"),
"member" => Some("member"),
"memv" => Some("memv"),
"memq" => Some("memq"),
"assoc" => Some("assoc"),
"assv" => Some("assv"),
"assq" => Some("assq"),
"null?" => Some("null?"),
"pair?" => Some("pair?"),
"list?" => Some("list?"),
// R4RS predicates
"boolean?" => Some("boolean?"),
"symbol?" => Some("symbol?"),
"char?" => Some("char?"),
"string?" => Some("string?"),
"number?" => Some("number?"),
"integer?" => Some("integer?"),
"real?" => Some("real?"),
"exact?" => Some("exact?"),
"inexact?" => Some("inexact?"),
"procedure?" => Some("procedure?"),
"vector?" => Some("vector?"),
"zero?" => Some("zero?"),
"positive?" => Some("positive?"),
"negative?" => Some("negative?"),
"odd?" => Some("odd?"),
"even?" => Some("even?"),
// R4RS comparison
"eq?" => Some("eq?"),
"eqv?" => Some("eqv?"),
"equal?" => Some("equal?"),
"=" => Some("="),
"<" => Some("<"),
">" => Some(">"),
"<=" => Some("<="),
">=" => Some(">="),
// R4RS arithmetic
"+" => Some("+"),
"-" => Some("-"),
"*" => Some("*"),
"/" => Some("/"),
"quotient" => Some("quotient"),
"remainder" => Some("remainder"),
"modulo" => Some("modulo"),
"abs" => Some("abs"),
"max" => Some("max"),
"min" => Some("min"),
"floor" => Some("floor"),
"ceiling" => Some("ceiling"),
"truncate" => Some("truncate"),
"round" => Some("round"),
"sqrt" => Some("sqrt"),
"expt" => Some("expt"),
"exp" => Some("exp"),
"log" => Some("log"),
"sin" => Some("sin"),
"cos" => Some("cos"),
"tan" => Some("tan"),
"asin" => Some("asin"),
"acos" => Some("acos"),
"atan" => Some("atan"),
"number->string" => Some("number->string"),
"string->number" => Some("string->number"),
// R4RS strings
"string" => Some("string"),
"string-append" => Some("string-append"),
"substring" => Some("substring"),
"string-ref" => Some("string-ref"),
"string-length" => Some("string-length"),
"string=?" => Some("string=?"),
"string<?" => Some("string<?"),
"string>?" => Some("string>?"),
"string<=?" => Some("string<=?"),
"string>=?" => Some("string>=?"),
"string-ci=?" => Some("string-ci=?"),
"string-ci<?" => Some("string-ci<?"),
"string-ci>?" => Some("string-ci>?"),
"string-ci<=?" => Some("string-ci<=?"),
"string-ci>=?" => Some("string-ci>=?"),
"string->list" => Some("string->list"),
"list->string" => Some("list->string"),
"symbol->string" => Some("symbol->string"),
"string->symbol" => Some("string->symbol"),
"keyword?" => Some("keyword?"),
"keyword->string" => Some("keyword->string"),
"string->keyword" => Some("string->keyword"),
// R4RS characters
"char=?" => Some("char=?"),
"char<?" => Some("char<?"),
"char>?" => Some("char>?"),
"char<=?" => Some("char<=?"),
"char>=?" => Some("char>=?"),
"char-ci=?" => Some("char-ci=?"),
"char-ci<?" => Some("char-ci<?"),
"char-ci>?" => Some("char-ci>?"),
"char-ci<=?" => Some("char-ci<=?"),
"char-ci>=?" => Some("char-ci>=?"),
"char-alphabetic?" => Some("char-alphabetic?"),
"char-numeric?" => Some("char-numeric?"),
"char-whitespace?" => Some("char-whitespace?"),
"char-upper-case?" => Some("char-upper-case?"),
"char-lower-case?" => Some("char-lower-case?"),
"char-upcase" => Some("char-upcase"),
"char-downcase" => Some("char-downcase"),
"char->integer" => Some("char->integer"),
"integer->char" => Some("integer->char"),
"char-property" => Some("char-property"),
"char-script-case" => Some("char-script-case"),
// R4RS vectors
"vector" => Some("vector"),
"make-vector" => Some("make-vector"),
"vector-ref" => Some("vector-ref"),
"vector-set!" => Some("vector-set!"),
"vector-length" => Some("vector-length"),
"vector->list" => Some("vector->list"),
"list->vector" => Some("list->vector"),
"vector-fill!" => Some("vector-fill!"),
// R4RS logic
"not" => Some("not"),
// R4RS I/O (excluding special forms)
"display" => Some("display"),
"write" => Some("write"),
"newline" => Some("newline"),
"read" => Some("read"),
// Note: "load" is NOT included - it's a special form with eval_load
// Note: R4RS higher-order "map", "for-each", "apply" are NOT included
// They are special forms with eval_map, eval_for_each, eval_apply
// DSSSL grove primitives
"node?" => Some("node?"),
"sosofo?" => Some("sosofo?"),
"current-node" => Some("current-node"),
"gi" => Some("gi"),
"id" => Some("id"),
"data" => Some("data"),
"node-property" => Some("node-property"),
"attribute-string" => Some("attribute-string"),
"parent" => Some("parent"),
"ancestor" => Some("ancestor"),
"children" => Some("children"),
"descendants" => Some("descendants"),
"follow" => Some("follow"),
"preced" => Some("preced"),
"ipreced" => Some("ipreced"),
"attributes" => Some("attributes"),
"ancestors" => Some("ancestors"),
"document-element" => Some("document-element"),
"have-ancestor?" => Some("have-ancestor?"),
"hierarchical-number" => Some("hierarchical-number"),
"hierarchical-number-recursive" => Some("hierarchical-number-recursive"),
"absolute-first-sibling?" => Some("absolute-first-sibling?"),
"absolute-last-sibling?" => Some("absolute-last-sibling?"),
"select-elements" => Some("select-elements"),
"element-with-id" => Some("element-with-id"),
"match-element?" => Some("match-element?"),
"first-sibling?" => Some("first-sibling?"),
"last-sibling?" => Some("last-sibling?"),
"child-number" => Some("child-number"),
"element-number" => Some("element-number"),
"node-list?" => Some("node-list?"),
"node-list-first" => Some("node-list-first"),
"node-list-rest" => Some("node-list-rest"),
"node-list-length" => Some("node-list-length"),
"empty-node-list" => Some("empty-node-list"),
"node-list-empty?" => Some("node-list-empty?"),
"node-list-head" => Some("node-list-head"),
"node-list-tail" => Some("node-list-tail"),
"node-list-sublist" => Some("node-list-sublist"),
"node-list-ref" => Some("node-list-ref"),
"node-list-reduce" => Some("node-list-reduce"),
"node-list-reduce-right" => Some("node-list-reduce-right"),
"node-list-map" => Some("node-list-map"),
"node-list-filter" => Some("node-list-filter"),
"node-list-contains?" => Some("node-list-contains?"),
"node-list-some?" => Some("node-list-some?"),
"node-list-every?" => Some("node-list-every?"),
"node-list->list" => Some("node-list->list"),
"node-list-union" => Some("node-list-union"),
"node-list-intersection" => Some("node-list-intersection"),
"node-list-difference" => Some("node-list-difference"),
"node-list-remove-duplicates" => Some("node-list-remove-duplicates"),
"node-list-last" => Some("node-list-last"),
"node-list-reverse" => Some("node-list-reverse"),
// DSSSL processing
// Note: "process-children" and "process-node-list" are NOT included
// They are special forms with eval_process_children, eval_process_node_list
"literal" => Some("literal"),
"next-match" => Some("next-match"),
"sosofo-append" => Some("sosofo-append"),
"empty-sosofo" => Some("empty-sosofo"),
"format-number" => Some("format-number"),
"format-number-list" => Some("format-number-list"),
// DSSSL entity/notation primitives
"entity-system-id" => Some("entity-system-id"),
"entity-public-id" => Some("entity-public-id"),
"entity-text" => Some("entity-text"),
"entity-type" => Some("entity-type"),
"notation-system-id" => Some("notation-system-id"),
"notation-public-id" => Some("notation-public-id"),
// DSSSL quantity primitives (stubs)
"quantity?" => Some("quantity?"),
"quantity" => Some("quantity"),
"quantity->number" => Some("quantity->number"),
"number->quantity" => Some("number->quantity"),
"quantity-convert" => Some("quantity-convert"),
"device-length" => Some("device-length"),
"label-distance" => Some("label-distance"),
// DSSSL color primitives (stubs)
"color?" => Some("color?"),
"color" => Some("color"),
"color-space?" => Some("color-space?"),
"color-space" => Some("color-space"),
// DSSSL address primitives (stubs)
"address?" => Some("address?"),
"address" => Some("address"),
"address-local?" => Some("address-local?"),
"address-visited?" => Some("address-visited?"),
// DSSSL glyph primitives (stubs)
"glyph-id?" => Some("glyph-id?"),
"glyph-id" => Some("glyph-id"),
"glyph-subst-table?" => Some("glyph-subst-table?"),
"glyph-subst-table" => Some("glyph-subst-table"),
"glyph-subst" => Some("glyph-subst"),
// DSSSL spacing primitives (stubs)
"display-space" => Some("display-space"),
"inline-space" => Some("inline-space"),
"display-space?" => Some("display-space?"),
"inline-space?" => Some("inline-space?"),
// OpenJade extensions
"time" => Some("time"),
"time->string" => Some("time->string"),
"time<=?" => Some("time<=?"),
"time<?" => Some("time<?"),
"time>=?" => Some("time>=?"),
"time>?" => Some("time>?"),
"language?" => Some("language?"),
"language" => Some("language"),
"style?" => Some("style?"),
"string-equiv?" => Some("string-equiv?"),
"label-length" => Some("label-length"),
"external-procedure" => Some("external-procedure"),
"declaration" => Some("declaration"),
"dtd" => Some("dtd"),
"epilog" => Some("epilog"),
"prolog" => Some("prolog"),
"sgml-declaration" => Some("sgml-declaration"),
"sgml-parse" => Some("sgml-parse"),
"entity-address" => Some("entity-address"),
"entity-generated-system-id" => Some("entity-generated-system-id"),
"entity-name-normalize" => Some("entity-name-normalize"),
"general-name-normalize" => Some("general-name-normalize"),
"normalize" => Some("normalize"),
"first-child-gi" => Some("first-child-gi"),
"tree-root" => Some("tree-root"),
"declare-default-language" => Some("declare-default-language"),
"read-entity" => Some("read-entity"),
"set-visited!" => Some("set-visited!"),
"sosofo-contains-node?" => Some("sosofo-contains-node?"),
"page-number-sosofo" => Some("page-number-sosofo"),
"ifollow" => Some("ifollow"),
"with-language" => Some("with-language"),
"all-element-number" => Some("all-element-number"),
"ancestor-child-number" => Some("ancestor-child-number"),
"element-number-list" => Some("element-number-list"),
"inherited-attribute-string" => Some("inherited-attribute-string"),
"inherited-element-attribute-string" => Some("inherited-element-attribute-string"),
"inherited-start-indent" => Some("inherited-start-indent"),
"inherited-end-indent" => Some("inherited-end-indent"),
"inherited-line-spacing" => Some("inherited-line-spacing"),
"inherited-font-family-name" => Some("inherited-font-family-name"),
"inherited-font-size" => Some("inherited-font-size"),
"inherited-font-weight" => Some("inherited-font-weight"),
"inherited-font-posture" => Some("inherited-font-posture"),
"inherited-dbhtml-value" => Some("inherited-dbhtml-value"),
"inherited-pi-value" => Some("inherited-pi-value"),
"node-list" => Some("node-list"),
"node-list=?" => Some("node-list=?"),
"node-list-count" => Some("node-list-count"),
"node-list-union-map" => Some("node-list-union-map"),
"node-list-symmetrical-difference" => Some("node-list-symmetrical-difference"),
"node-list-address" => Some("node-list-address"),
"node-list-error" => Some("node-list-error"),
"node-list-no-order" => Some("node-list-no-order"),
"origin-to-subnode-rel-forest-addr" => Some("origin-to-subnode-rel-forest-addr"),
"named-node" => Some("named-node"),
"named-node-list?" => Some("named-node-list?"),
"named-node-list-names" => Some("named-node-list-names"),
"select-by-class" => Some("select-by-class"),
"select-children" => Some("select-children"),
"process-children-trim" => Some("process-children-trim"),
"process-element-with-id" => Some("process-element-with-id"),
"process-first-descendant" => Some("process-first-descendant"),
"process-matching-children" => Some("process-matching-children"),
// Additional utility primitives
"add" => Some("add"),
"divide" => Some("divide"),
"equal" => Some("equal"),
"char-eq" => Some("char-eq"),
"char-lt" => Some("char-lt"),
"error" => Some("error"),
"eof-object?" => Some("eof-object?"),
"debug" => Some("debug"),
"current-language" => Some("current-language"),
"current-mode" => Some("current-mode"),
"current-node-address" => Some("current-node-address"),
"current-node-page-number-sosofo" => Some("current-node-page-number-sosofo"),
// Not a known primitive
_ => None,
}
}
// =========================================================================
// Arena Conversion Layer (Phase 2 migration)
// =========================================================================
//
// These functions convert between old Value and new ValueId.
// During Phase 2, hot primitives use arena (ValueId), while the rest
// of the system still uses Value. These converters bridge the gap.
/// Convert Value to ValueId (for hot primitives)
fn value_to_arena(&mut self, value: &Value) -> ValueId {
use crate::scheme::arena::{NIL_ID, TRUE_ID, FALSE_ID};
match value {
Value::Nil => NIL_ID,
Value::Bool(true) => TRUE_ID,
Value::Bool(false) => FALSE_ID,
Value::Integer(n) => self.arena.int(*n),
Value::Real(f) => self.arena.real(*f),
Value::Quantity { magnitude, unit } => {
self.arena.alloc(ValueData::Quantity { magnitude: *magnitude, unit: *unit })
}
Value::String(s) => self.arena.string((**s).clone()),
Value::Symbol(s) => self.arena.symbol(s.clone()),
Value::Keyword(k) => self.arena.keyword(k.clone()),
Value::Char(c) => self.arena.char(*c),
Value::Pair(pair) => {
let p = pair.borrow();
let car = self.value_to_arena(&p.car);
let cdr = self.value_to_arena(&p.cdr);
if let Some(pos) = &p.pos {
self.arena.cons_with_pos(car, cdr, pos.clone())
} else {
self.arena.cons(car, cdr)
}
}
Value::Vector(vec) => {
let v = vec.borrow();
let elements: Vec<ValueId> = v.iter().map(|val| self.value_to_arena(val)).collect();
self.arena.vector(elements)
}
Value::Node(node) => {
self.arena.alloc(ValueData::Node(node.clone()))
}
Value::NodeList(node_list) => {
self.arena.alloc(ValueData::NodeList(node_list.clone()))
}
Value::Sosofo => {
self.arena.alloc(ValueData::Sosofo)
}
Value::Unspecified => {
crate::scheme::arena::UNSPECIFIED_ID
}
_ => {
// For now, unsupported types return NIL
NIL_ID
}
}
}
/// Convert ValueId to Value (from hot primitives)
fn arena_to_value(&self, id: ValueId) -> Value {
use crate::scheme::arena::{NIL_ID, TRUE_ID, FALSE_ID};
// Fast path for constants
if id == NIL_ID {
return Value::Nil;
}
if id == TRUE_ID {
return Value::Bool(true);
}
if id == FALSE_ID {
return Value::Bool(false);
}
match self.arena.get(id) {
ValueData::Nil => Value::Nil,
ValueData::Bool(b) => Value::Bool(*b),
ValueData::Integer(n) => Value::Integer(*n),
ValueData::Real(f) => Value::Real(*f),
ValueData::Quantity { magnitude, unit } => {
Value::Quantity { magnitude: *magnitude, unit: *unit }
}
ValueData::String(s) => Value::String(Gc::new(s.clone())),
ValueData::Symbol(s) => Value::Symbol(s.clone()),
ValueData::Keyword(k) => Value::Keyword(k.clone()),
ValueData::Char(c) => Value::Char(*c),
ValueData::Pair { car, cdr, pos } => {
let car_val = self.arena_to_value(*car);
let cdr_val = self.arena_to_value(*cdr);
if let Some(p) = pos {
Value::cons_with_pos(car_val, cdr_val, p.clone())
} else {
Value::cons(car_val, cdr_val)
}
}
ValueData::Vector(elements) => {
let vals: Vec<Value> = elements.iter().map(|id| self.arena_to_value(*id)).collect();
Value::vector(vals)
}
ValueData::Node(node) => {
Value::Node(node.clone())
}
ValueData::NodeList(node_list) => {
Value::NodeList(node_list.clone())
}
ValueData::Sosofo => Value::Sosofo,
ValueData::Unspecified => Value::Unspecified,
ValueData::Error => Value::Error,
ValueData::Procedure(_) => {
// Procedures cannot be converted back to old-style values
// This shouldn't happen in normal operation
Value::Unspecified
}
}
}
/// Apply arena primitive (Phase 2+3 hot path)
fn apply_primitive(&mut self, name: &str, args: &[Value]) -> EvalResult {
use crate::scheme::primitives::{
car, cdr, cons, null, equal,
cadr, caddr, cadddr, list, length,
reverse, append, list_p, list_ref,
pair_p, number_p, integer_p, real_p,
string_p, symbol_p, char_p, boolean_p,
zero_p, positive_p, negative_p, odd_p, even_p,
add, subtract, multiply, divide,
quotient, remainder, modulo,
num_eq, num_lt, num_gt, num_le, num_ge,
abs, min, max,
floor, ceiling, truncate, round,
sqrt, sin, cos, tan,
asin, acos, atan, exp, log, expt,
string_length, string_ref, substring, string_append,
string_eq, string_lt, string_gt, string_le, string_ge,
string_ci_eq, string_ci_lt, string_ci_gt,
string_ci_le, string_ci_ge,
char_eq, char_lt, char_gt, char_le, char_ge,
char_ci_eq, char_ci_lt, char_ci_gt, char_ci_le, char_ci_ge,
char_upcase, char_downcase,
char_alphabetic_p, char_numeric_p, char_whitespace_p,
char_to_integer, integer_to_char,
char_property, char_script_case,
symbol_to_string, string_to_symbol,
keyword_p, keyword_to_string, string_to_keyword,
memq, memv, member,
assq, assv, assoc,
not, eq_p, eqv_p,
caar, cdar, cddr,
caaar, caadr, cadar,
cdaar, cdadr, cddar, cdddr,
vector, make_vector, vector_length,
vector_ref, vector_set,
vector_to_list, list_to_vector, vector_fill,
vector_p, procedure_p,
set_car, set_cdr, list_tail,
string_upcase, string_downcase, case_fold_down,
string_index,
string_to_list, list_to_string,
gcd, lcm,
exact_to_inexact, inexact_to_exact,
make_string, string, reverse_bang,
string_set, string_copy, string_fill,
char_lower_case_p, char_upper_case_p,
last, last_pair, list_copy,
append_bang, iota,
take, drop, split_at,
filter, remove,
numerator, denominator, rationalize,
angle, magnitude, string_to_number_radix,
number_to_string_radix,
null_list_p, improper_list_p, circular_list_p,
bitwise_and, bitwise_ior, bitwise_xor, bitwise_not,
arithmetic_shift, bit_extract,
bitwise_bit_set_p, bitwise_bit_count,
display, newline, write, write_char,
read_char, eof_object_p,
format_number, format_number_list,
empty_sosofo, sosofo_append, if_first_page, if_front_page,
current_node,
gi, data, id,
children, parent, attributes,
node_list_p, empty_node_list, node_list_empty_p,
node_list_length, node_list_first,
attribute_string,
node_list_rest, node_list_ref, node_list_reverse,
node_p, sosofo_p, quantity_p,
color_p, color, display_space_p, inline_space_p,
quantity_to_number, number_to_quantity, quantity_convert,
device_length, label_distance,
ancestor, descendants, follow, preced, ipreced,
node_list_last, node_list_union, node_list_intersection,
node_list_difference, node_list_remove_duplicates,
select_elements, first_sibling_p, last_sibling_p,
child_number, element_with_id,
element_number, hierarchical_number, hierarchical_number_recursive,
ancestors, document_element, have_ancestor_p,
match_element_p, node_list_map,
node_property, absolute_first_sibling_p, absolute_last_sibling_p,
node_list_to_list, node_list_contains_p,
entity_system_id, entity_public_id, entity_type,
notation_system_id, notation_public_id,
current_language, current_mode, current_node_address,
current_node_page_number_sosofo, debug,
exact_p, inexact_p, error,
address_p, address_local_p, address_visited_p,
color_space_p, color_space, display_space, inline_space,
glyph_id_p, glyph_id, glyph_subst_table_p,
glyph_subst_table, glyph_subst,
time, time_to_string, time_le, time_lt,
time_ge, time_gt,
language_p, language, style_p,
string_equiv_p, label_length, external_procedure,
declaration, dtd, epilog, prolog,
sgml_declaration, sgml_parse,
entity_address, entity_generated_system_id,
entity_name_normalize, general_name_normalize, normalize,
first_child_gi, tree_root, declare_default_language,
read_entity, set_visited,
sosofo_contains_node_p, page_number_sosofo, ifollow, with_language,
all_element_number, ancestor_child_number, element_number_list,
inherited_attribute_string, inherited_element_attribute_string,
inherited_start_indent, inherited_end_indent, inherited_line_spacing,
inherited_font_family_name, inherited_font_size, inherited_font_weight,
inherited_font_posture, inherited_dbhtml_value, inherited_pi_value,
node_list, node_list_eq_p,
node_list_union_map, node_list_symmetrical_difference, node_list_count,
node_list_address, node_list_error, node_list_no_order,
origin_to_subnode_rel_forest_addr,
named_node, named_node_list_p, named_node_list_names,
select_by_class, select_children,
process_children_trim, process_element_with_id, process_first_descendant,
process_matching_children, next_match,
};
// Special handling for eq? and eqv? - check pointer equality at Value level
// to preserve identity semantics when converting from Value to ValueId
if (name == "eq?" || name == "eqv?") && args.len() == 2 {
// Check if the two Values are pointer-equal (same object)
let ptr_equal = match (&args[0], &args[1]) {
(Value::Pair(p1), Value::Pair(p2)) => gc::Gc::ptr_eq(p1, p2),
(Value::String(s1), Value::String(s2)) => gc::Gc::ptr_eq(s1, s2),
(Value::Procedure(pr1), Value::Procedure(pr2)) => gc::Gc::ptr_eq(pr1, pr2),
_ => false,
};
if ptr_equal {
return Ok(Value::bool(true));
}
}
// Special handling for type predicates that check types not convertible to arena
if name == "vector?" && args.len() == 1 {
return Ok(Value::bool(matches!(args[0], Value::Vector(_))));
}
if name == "procedure?" && args.len() == 1 {
return Ok(Value::bool(matches!(args[0], Value::Procedure(_))));
}
// Convert args to arena
let arena_args: Vec<ValueId> = args.iter().map(|v| self.value_to_arena(v)).collect();
// Call arena primitive
let result_id = match name {
"car" => car(&self.arena, &arena_args),
"cdr" => cdr(&self.arena, &arena_args),
"cons" => cons(&mut self.arena, &arena_args),
"null?" => null(&self.arena, &arena_args),
"equal?" => equal(&self.arena, &arena_args),
"cadr" => cadr(&self.arena, &arena_args),
"caddr" => caddr(&self.arena, &arena_args),
"cadddr" => cadddr(&self.arena, &arena_args),
"list" => list(&mut self.arena, &arena_args),
"length" => length(&mut self.arena, &arena_args),
"reverse" => reverse(&mut self.arena, &arena_args),
"append" => append(&mut self.arena, &arena_args),
"list?" => list_p(&self.arena, &arena_args),
"list-ref" => list_ref(&self.arena, &arena_args),
"pair?" => pair_p(&self.arena, &arena_args),
"number?" => number_p(&self.arena, &arena_args),
"integer?" => integer_p(&self.arena, &arena_args),
"real?" => real_p(&self.arena, &arena_args),
"string?" => string_p(&self.arena, &arena_args),
"symbol?" => symbol_p(&self.arena, &arena_args),
"char?" => char_p(&self.arena, &arena_args),
"boolean?" => boolean_p(&self.arena, &arena_args),
"zero?" => zero_p(&self.arena, &arena_args),
"positive?" => positive_p(&self.arena, &arena_args),
"negative?" => negative_p(&self.arena, &arena_args),
"odd?" => odd_p(&self.arena, &arena_args),
"even?" => even_p(&self.arena, &arena_args),
"+" => add(&mut self.arena, &arena_args),
"-" => subtract(&mut self.arena, &arena_args),
"*" => multiply(&mut self.arena, &arena_args),
"/" => divide(&mut self.arena, &arena_args),
"quotient" => quotient(&mut self.arena, &arena_args),
"remainder" => remainder(&mut self.arena, &arena_args),
"modulo" => modulo(&mut self.arena, &arena_args),
"=" => num_eq(&self.arena, &arena_args),
"<" => num_lt(&self.arena, &arena_args),
">" => num_gt(&self.arena, &arena_args),
"<=" => num_le(&self.arena, &arena_args),
">=" => num_ge(&self.arena, &arena_args),
"abs" => abs(&mut self.arena, &arena_args),
"min" => min(&mut self.arena, &arena_args),
"max" => max(&mut self.arena, &arena_args),
"floor" => floor(&mut self.arena, &arena_args),
"ceiling" => ceiling(&mut self.arena, &arena_args),
"truncate" => truncate(&mut self.arena, &arena_args),
"round" => round(&mut self.arena, &arena_args),
"sqrt" => sqrt(&mut self.arena, &arena_args),
"sin" => sin(&mut self.arena, &arena_args),
"cos" => cos(&mut self.arena, &arena_args),
"tan" => tan(&mut self.arena, &arena_args),
"asin" => asin(&mut self.arena, &arena_args),
"acos" => acos(&mut self.arena, &arena_args),
"atan" => atan(&mut self.arena, &arena_args),
"exp" => exp(&mut self.arena, &arena_args),
"log" => log(&mut self.arena, &arena_args),
"expt" => expt(&mut self.arena, &arena_args),
"string-length" => string_length(&mut self.arena, &arena_args),
"string-ref" => string_ref(&mut self.arena, &arena_args),
"substring" => substring(&mut self.arena, &arena_args),
"string-append" => string_append(&mut self.arena, &arena_args),
"string=?" => string_eq(&self.arena, &arena_args),
"string<?" => string_lt(&self.arena, &arena_args),
"string>?" => string_gt(&self.arena, &arena_args),
"string<=?" => string_le(&self.arena, &arena_args),
"string>=?" => string_ge(&self.arena, &arena_args),
"string-ci=?" => string_ci_eq(&self.arena, &arena_args),
"string-ci<?" => string_ci_lt(&self.arena, &arena_args),
"string-ci>?" => string_ci_gt(&self.arena, &arena_args),
"string-ci<=?" => string_ci_le(&self.arena, &arena_args),
"string-ci>=?" => string_ci_ge(&self.arena, &arena_args),
"char=?" => char_eq(&self.arena, &arena_args),
"char<?" => char_lt(&self.arena, &arena_args),
"char>?" => char_gt(&self.arena, &arena_args),
"char<=?" => char_le(&self.arena, &arena_args),
"char>=?" => char_ge(&self.arena, &arena_args),
"char-ci=?" => char_ci_eq(&self.arena, &arena_args),
"char-ci<?" => char_ci_lt(&self.arena, &arena_args),
"char-ci>?" => char_ci_gt(&self.arena, &arena_args),
"char-ci<=?" => char_ci_le(&self.arena, &arena_args),
"char-ci>=?" => char_ci_ge(&self.arena, &arena_args),
"char-upcase" => char_upcase(&mut self.arena, &arena_args),
"char-downcase" => char_downcase(&mut self.arena, &arena_args),
"char-alphabetic?" => char_alphabetic_p(&self.arena, &arena_args),
"char-numeric?" => char_numeric_p(&self.arena, &arena_args),
"char-whitespace?" => char_whitespace_p(&self.arena, &arena_args),
"char->integer" => char_to_integer(&mut self.arena, &arena_args),
"integer->char" => integer_to_char(&mut self.arena, &arena_args),
"char-property" => char_property(&mut self.arena, &arena_args),
"char-script-case" => char_script_case(&mut self.arena, &arena_args),
"symbol->string" => symbol_to_string(&mut self.arena, &arena_args),
"string->symbol" => string_to_symbol(&mut self.arena, &arena_args),
"keyword?" => keyword_p(&self.arena, &arena_args),
"keyword->string" => keyword_to_string(&mut self.arena, &arena_args),
"string->keyword" => string_to_keyword(&mut self.arena, &arena_args),
"memq" => memq(&self.arena, &arena_args),
"memv" => memv(&self.arena, &arena_args),
"member" => member(&self.arena, &arena_args),
"assq" => assq(&self.arena, &arena_args),
"assv" => assv(&self.arena, &arena_args),
"assoc" => assoc(&self.arena, &arena_args),
"not" => not(&self.arena, &arena_args),
"eq?" => eq_p(&self.arena, &arena_args),
"eqv?" => eqv_p(&self.arena, &arena_args),
"caar" => caar(&self.arena, &arena_args),
"cdar" => cdar(&self.arena, &arena_args),
"cddr" => cddr(&self.arena, &arena_args),
"caaar" => caaar(&self.arena, &arena_args),
"caadr" => caadr(&self.arena, &arena_args),
"cadar" => cadar(&self.arena, &arena_args),
"cdaar" => cdaar(&self.arena, &arena_args),
"cdadr" => cdadr(&self.arena, &arena_args),
"cddar" => cddar(&self.arena, &arena_args),
"cdddr" => cdddr(&self.arena, &arena_args),
"vector" => vector(&mut self.arena, &arena_args),
"make-vector" => make_vector(&mut self.arena, &arena_args),
"vector-length" => vector_length(&mut self.arena, &arena_args),
"vector-ref" => vector_ref(&self.arena, &arena_args),
"vector-set!" => vector_set(&mut self.arena, &arena_args),
"vector->list" => vector_to_list(&mut self.arena, &arena_args),
"list->vector" => list_to_vector(&mut self.arena, &arena_args),
"vector-fill!" => vector_fill(&mut self.arena, &arena_args),
"vector?" => vector_p(&self.arena, &arena_args),
"procedure?" => procedure_p(&self.arena, &arena_args),
"set-car!" => set_car(&mut self.arena, &arena_args),
"set-cdr!" => set_cdr(&mut self.arena, &arena_args),
"list-tail" => list_tail(&self.arena, &arena_args),
"string-upcase" => string_upcase(&mut self.arena, &arena_args),
"string-downcase" => string_downcase(&mut self.arena, &arena_args),
"case-fold-down" => case_fold_down(&mut self.arena, &arena_args), // DSSSL alias for string-downcase
"string-index" => string_index(&mut self.arena, &arena_args),
"string->number" => string_to_number_radix(&mut self.arena, &arena_args), // Updated to support radix
"number->string" => number_to_string_radix(&mut self.arena, &arena_args), // Updated to support radix
"string->list" => string_to_list(&mut self.arena, &arena_args),
"list->string" => list_to_string(&mut self.arena, &arena_args),
"gcd" => gcd(&mut self.arena, &arena_args),
"lcm" => lcm(&mut self.arena, &arena_args),
"exact->inexact" => exact_to_inexact(&mut self.arena, &arena_args),
"inexact->exact" => inexact_to_exact(&mut self.arena, &arena_args),
"make-string" => make_string(&mut self.arena, &arena_args),
"string" => string(&mut self.arena, &arena_args),
"reverse!" => reverse_bang(&mut self.arena, &arena_args),
"string-set!" => string_set(&mut self.arena, &arena_args),
"string-copy" => string_copy(&mut self.arena, &arena_args),
"string-fill!" => string_fill(&mut self.arena, &arena_args),
"char-lower-case?" => char_lower_case_p(&self.arena, &arena_args),
"char-upper-case?" => char_upper_case_p(&self.arena, &arena_args),
"last" => last(&self.arena, &arena_args),
"last-pair" => last_pair(&self.arena, &arena_args),
"list-copy" => list_copy(&mut self.arena, &arena_args),
"append!" => append_bang(&mut self.arena, &arena_args),
"iota" => iota(&mut self.arena, &arena_args),
"take" => take(&mut self.arena, &arena_args),
"drop" => drop(&self.arena, &arena_args),
"split-at" => split_at(&mut self.arena, &arena_args),
"filter" => filter(&self.arena, &arena_args),
"remove" => remove(&self.arena, &arena_args),
"numerator" => numerator(&mut self.arena, &arena_args),
"denominator" => denominator(&mut self.arena, &arena_args),
"rationalize" => rationalize(&self.arena, &arena_args),
"angle" => angle(&mut self.arena, &arena_args),
"magnitude" => magnitude(&mut self.arena, &arena_args),
"null-list?" => null_list_p(&self.arena, &arena_args),
"improper-list?" => improper_list_p(&self.arena, &arena_args),
"circular-list?" => circular_list_p(&self.arena, &arena_args),
"bitwise-and" => bitwise_and(&mut self.arena, &arena_args),
"bitwise-ior" => bitwise_ior(&mut self.arena, &arena_args),
"bitwise-xor" => bitwise_xor(&mut self.arena, &arena_args),
"bitwise-not" => bitwise_not(&mut self.arena, &arena_args),
"arithmetic-shift" => arithmetic_shift(&mut self.arena, &arena_args),
"bit-extract" => bit_extract(&mut self.arena, &arena_args),
"bitwise-bit-set?" => bitwise_bit_set_p(&self.arena, &arena_args),
"bitwise-bit-count" => bitwise_bit_count(&mut self.arena, &arena_args),
"display" => display(&self.arena, &arena_args),
"newline" => newline(&self.arena, &arena_args),
"write" => write(&self.arena, &arena_args),
"write-char" => write_char(&self.arena, &arena_args),
"read-char" => read_char(&self.arena, &arena_args),
"eof-object?" => eof_object_p(&self.arena, &arena_args),
"format-number" => format_number(&mut self.arena, &arena_args),
"format-number-list" => format_number_list(&mut self.arena, &arena_args),
"empty-sosofo" => empty_sosofo(&mut self.arena, &arena_args),
"sosofo-append" => sosofo_append(&mut self.arena, &arena_args),
"if-first-page" => if_first_page(&mut self.arena, &arena_args),
"if-front-page" => if_front_page(&mut self.arena, &arena_args),
"current-node" => current_node(&mut self.arena, &arena_args),
"gi" => gi(&mut self.arena, &arena_args),
"data" => data(&mut self.arena, &arena_args),
"id" => id(&mut self.arena, &arena_args),
"children" => children(&mut self.arena, &arena_args),
"parent" => parent(&mut self.arena, &arena_args),
"attributes" => attributes(&mut self.arena, &arena_args),
"node-list?" => node_list_p(&self.arena, &arena_args),
"empty-node-list" => empty_node_list(&mut self.arena, &arena_args),
"node-list-empty?" => node_list_empty_p(&self.arena, &arena_args),
"node-list-length" => node_list_length(&mut self.arena, &arena_args),
"node-list-first" => node_list_first(&mut self.arena, &arena_args),
"attribute-string" => attribute_string(&mut self.arena, &arena_args),
"node-list-rest" => node_list_rest(&mut self.arena, &arena_args),
"node-list-ref" => node_list_ref(&mut self.arena, &arena_args),
"node-list-reverse" => node_list_reverse(&mut self.arena, &arena_args),
"node?" => node_p(&self.arena, &arena_args),
"sosofo?" => sosofo_p(&self.arena, &arena_args),
"quantity?" => quantity_p(&self.arena, &arena_args),
"color?" => color_p(&self.arena, &arena_args),
"color" => color(&mut self.arena, &arena_args),
"display-space?" => display_space_p(&self.arena, &arena_args),
"inline-space?" => inline_space_p(&self.arena, &arena_args),
"quantity->number" => quantity_to_number(&mut self.arena, &arena_args),
"number->quantity" => number_to_quantity(&mut self.arena, &arena_args),
"quantity-convert" => quantity_convert(&mut self.arena, &arena_args),
"device-length" => device_length(&mut self.arena, &arena_args),
"label-distance" => label_distance(&mut self.arena, &arena_args),
"ancestor" => ancestor(&mut self.arena, &arena_args),
"descendants" => descendants(&mut self.arena, &arena_args),
"follow" => follow(&mut self.arena, &arena_args),
"preced" => preced(&mut self.arena, &arena_args),
"ipreced" => ipreced(&mut self.arena, &arena_args),
"node-list-last" => node_list_last(&mut self.arena, &arena_args),
"node-list-union" => node_list_union(&mut self.arena, &arena_args),
"node-list-intersection" => node_list_intersection(&mut self.arena, &arena_args),
"node-list-difference" => node_list_difference(&mut self.arena, &arena_args),
"node-list-remove-duplicates" => node_list_remove_duplicates(&mut self.arena, &arena_args),
"select-elements" => select_elements(&mut self.arena, &arena_args),
"first-sibling?" => first_sibling_p(&mut self.arena, &arena_args),
"last-sibling?" => last_sibling_p(&mut self.arena, &arena_args),
"child-number" => child_number(&mut self.arena, &arena_args),
"element-with-id" => element_with_id(&mut self.arena, &arena_args),
"element-number" => element_number(&mut self.arena, &arena_args),
"hierarchical-number" => hierarchical_number(&mut self.arena, &arena_args),
"hierarchical-number-recursive" => hierarchical_number_recursive(&mut self.arena, &arena_args),
"ancestors" => ancestors(&mut self.arena, &arena_args),
"document-element" => document_element(&mut self.arena, &arena_args),
"have-ancestor?" => have_ancestor_p(&mut self.arena, &arena_args),
"match-element?" => match_element_p(&mut self.arena, &arena_args),
"node-list-map" => node_list_map(&mut self.arena, &arena_args),
"node-property" => node_property(&mut self.arena, &arena_args),
"absolute-first-sibling?" => absolute_first_sibling_p(&mut self.arena, &arena_args),
"absolute-last-sibling?" => absolute_last_sibling_p(&mut self.arena, &arena_args),
"node-list->list" => node_list_to_list(&mut self.arena, &arena_args),
"node-list-contains?" => node_list_contains_p(&mut self.arena, &arena_args),
"entity-system-id" => entity_system_id(&mut self.arena, &arena_args),
"entity-public-id" => entity_public_id(&mut self.arena, &arena_args),
"entity-type" => entity_type(&mut self.arena, &arena_args),
"notation-system-id" => notation_system_id(&mut self.arena, &arena_args),
"notation-public-id" => notation_public_id(&mut self.arena, &arena_args),
"current-language" => current_language(&self.arena, &arena_args),
"current-mode" => current_mode(&self.arena, &arena_args),
"current-node-address" => current_node_address(&self.arena, &arena_args),
"current-node-page-number-sosofo" => current_node_page_number_sosofo(&mut self.arena, &arena_args),
"debug" => debug(&self.arena, &arena_args),
"add" => add(&mut self.arena, &arena_args),
"divide" => divide(&mut self.arena, &arena_args),
"equal" => equal(&self.arena, &arena_args),
"char-eq" => char_eq(&self.arena, &arena_args),
"char-lt" => char_lt(&self.arena, &arena_args),
"exact?" => exact_p(&self.arena, &arena_args),
"inexact?" => inexact_p(&self.arena, &arena_args),
"error" => error(&mut self.arena, &arena_args),
"address?" => address_p(&self.arena, &arena_args),
"address-local?" => address_local_p(&self.arena, &arena_args),
"address-visited?" => address_visited_p(&self.arena, &arena_args),
"color-space?" => color_space_p(&self.arena, &arena_args),
"color-space" => color_space(&self.arena, &arena_args),
"display-space" => display_space(&mut self.arena, &arena_args),
"inline-space" => inline_space(&mut self.arena, &arena_args),
"glyph-id?" => glyph_id_p(&self.arena, &arena_args),
"glyph-id" => glyph_id(&self.arena, &arena_args),
"glyph-subst-table?" => glyph_subst_table_p(&self.arena, &arena_args),
"glyph-subst-table" => glyph_subst_table(&self.arena, &arena_args),
"glyph-subst" => glyph_subst(&self.arena, &arena_args),
"time" => time(&self.arena, &arena_args),
"time->string" => time_to_string(&mut self.arena, &arena_args),
"time<=?" => time_le(&self.arena, &arena_args),
"time<?" => time_lt(&self.arena, &arena_args),
"time>=?" => time_ge(&self.arena, &arena_args),
"time>?" => time_gt(&self.arena, &arena_args),
"language?" => language_p(&self.arena, &arena_args),
"language" => language(&mut self.arena, &arena_args),
"style?" => style_p(&self.arena, &arena_args),
"string-equiv?" => string_equiv_p(&self.arena, &arena_args),
"label-length" => label_length(&mut self.arena, &arena_args),
"external-procedure" => external_procedure(&mut self.arena, &arena_args),
"declaration" => declaration(&self.arena, &arena_args),
"dtd" => dtd(&self.arena, &arena_args),
"epilog" => epilog(&self.arena, &arena_args),
"prolog" => prolog(&self.arena, &arena_args),
"sgml-declaration" => sgml_declaration(&self.arena, &arena_args),
"sgml-parse" => sgml_parse(&self.arena, &arena_args),
"entity-address" => entity_address(&self.arena, &arena_args),
"entity-generated-system-id" => entity_generated_system_id(&mut self.arena, &arena_args),
"entity-name-normalize" => entity_name_normalize(&mut self.arena, &arena_args),
"general-name-normalize" => general_name_normalize(&mut self.arena, &arena_args),
"normalize" => normalize(&mut self.arena, &arena_args),
"first-child-gi" => first_child_gi(&mut self.arena, &arena_args),
"tree-root" => tree_root(&mut self.arena, &arena_args),
"declare-default-language" => declare_default_language(&self.arena, &arena_args),
"read-entity" => read_entity(&mut self.arena, &arena_args),
"set-visited!" => set_visited(&self.arena, &arena_args),
"sosofo-contains-node?" => sosofo_contains_node_p(&self.arena, &arena_args),
"page-number-sosofo" => page_number_sosofo(&mut self.arena, &arena_args),
"ifollow" => ifollow(&self.arena, &arena_args),
"with-language" => with_language(&self.arena, &arena_args),
"all-element-number" => all_element_number(&mut self.arena, &arena_args),
"ancestor-child-number" => ancestor_child_number(&mut self.arena, &arena_args),
"element-number-list" => element_number_list(&self.arena, &arena_args),
"inherited-attribute-string" => inherited_attribute_string(&mut self.arena, &arena_args),
"inherited-element-attribute-string" => inherited_element_attribute_string(&mut self.arena, &arena_args),
"inherited-start-indent" => inherited_start_indent(&mut self.arena, &arena_args),
"inherited-end-indent" => inherited_end_indent(&mut self.arena, &arena_args),
"inherited-line-spacing" => inherited_line_spacing(&mut self.arena, &arena_args),
"inherited-font-family-name" => inherited_font_family_name(&mut self.arena, &arena_args),
"inherited-font-size" => inherited_font_size(&mut self.arena, &arena_args),
"inherited-font-weight" => inherited_font_weight(&mut self.arena, &arena_args),
"inherited-font-posture" => inherited_font_posture(&mut self.arena, &arena_args),
"inherited-dbhtml-value" => inherited_dbhtml_value(&mut self.arena, &arena_args),
"inherited-pi-value" => inherited_pi_value(&mut self.arena, &arena_args),
"node-list" => node_list(&mut self.arena, &arena_args),
"node-list=?" => node_list_eq_p(&self.arena, &arena_args),
"node-list-count" => node_list_count(&mut self.arena, &arena_args),
"node-list-union-map" => node_list_union_map(&self.arena, &arena_args),
"node-list-symmetrical-difference" => node_list_symmetrical_difference(&self.arena, &arena_args),
"node-list-address" => node_list_address(&self.arena, &arena_args),
"node-list-error" => node_list_error(&mut self.arena, &arena_args),
"node-list-no-order" => node_list_no_order(&self.arena, &arena_args),
"origin-to-subnode-rel-forest-addr" => origin_to_subnode_rel_forest_addr(&self.arena, &arena_args),
"named-node" => named_node(&self.arena, &arena_args),
"named-node-list?" => named_node_list_p(&self.arena, &arena_args),
"named-node-list-names" => named_node_list_names(&self.arena, &arena_args),
"select-by-class" => select_by_class(&self.arena, &arena_args),
"select-children" => select_children(&self.arena, &arena_args),
"process-children-trim" => process_children_trim(&self.arena, &arena_args),
"process-element-with-id" => process_element_with_id(&self.arena, &arena_args),
"process-first-descendant" => process_first_descendant(&self.arena, &arena_args),
"process-matching-children" => process_matching_children(&self.arena, &arena_args),
"next-match" => next_match(&self.arena, &arena_args),
// Special handling for literal - it's not an arena primitive
"literal" => {
// literal can take 1 or 2 arguments:
// (literal "text") or (literal data: "text")
// For now, we just extract the text from the first string argument
if args.is_empty() {
return Err(self.error_with_stack("literal: expected at least 1 argument".to_string()));
}
// Find the text argument - could be first arg or after a keyword
let text = if args.len() == 1 {
// (literal "text")
match &args[0] {
Value::String(s) => s.to_string(),
_ => return Err(self.error_with_stack("literal: argument must be a string".to_string())),
}
} else if args.len() == 2 {
// (literal data: "text") - second arg is the text
match &args[1] {
Value::String(s) => s.to_string(),
_ => return Err(self.error_with_stack("literal: text argument must be a string".to_string())),
}
} else {
return Err(self.error_with_stack(format!(
"literal: expected 1 or 2 arguments, got {}",
args.len()
)));
};
if let Some(ref backend) = self.backend {
backend.borrow_mut().formatting_instruction(&text)
.map_err(|e| self.error_with_stack(format!("Backend error: {}", e)))?;
}
return Ok(Value::Unspecified);
}
_ => unreachable!("apply_primitive called with non-arena primitive: {}", name),
}
.map_err(|e| self.error_with_stack(e))?;
// Convert result back to Value
Ok(self.arena_to_value(result_id))
}
/// Set the current node
pub fn set_current_node(&mut self, node: Box<dyn Node>) {
self.arena.current_node = Some(Rc::new(node));
}
/// Get the current node
pub fn current_node(&self) -> Option<Rc<Box<dyn Node>>> {
self.arena.current_node.clone()
}
/// Clear the current node
pub fn clear_current_node(&mut self) {
self.arena.current_node = None;
}
/// Restore current node from saved state
pub fn restore_current_node(&mut self, node: Option<Rc<Box<dyn Node>>>) {
self.arena.current_node = node;
}
// =========================================================================
// DSSSL Processing (OpenJade ProcessContext.cxx)
// =========================================================================
/// Start DSSSL processing from the root node
///
/// Corresponds to OpenJade's `ProcessContext::process()`.
/// After template loading, this triggers automatic tree processing.
pub fn process_root(&mut self, env: Gc<Environment>) -> EvalResult {
// Get the root node from the grove
let root_node = match self.grove() {
Some(grove) => grove.root(),
None => return Err(EvalError::new("No grove set".to_string())),
};
// Set as current node and start processing
self.set_current_node(root_node);
self.process_node(env)
}
/// Process the current node
///
/// Corresponds to OpenJade's `ProcessContext::processNode()`.
///
/// ## Algorithm (from OpenJade):
/// 1. If character data node, output directly
/// 2. If element node:
/// a. Find matching construction rule by GI
/// b. If rule found, evaluate it (returns sosofo)
/// c. If no rule, default behavior: process-children
pub fn process_node(&mut self, env: Gc<Environment>) -> EvalResult {
// Increment node counter and trigger periodic GC
self.nodes_processed += 1;
// Trigger GC every 100 nodes to prevent memory accumulation
if self.nodes_processed % 100 == 0 {
// Collect Gc-wrapped values (tree-walker mode)
gc::force_collect();
// Collect arena values (VM mode)
// Preserve VM globals as GC roots
let roots: Vec<_> = self.vm_globals.values().copied().collect();
self.arena.gc(&roots);
}
let node = match self.current_node() {
Some(n) => n.clone(),
None => return Err(EvalError::new("No current node".to_string())),
};
// Get element name (GI)
let gi = match node.gi() {
Some(gi) => gi.to_string(),
None => {
// Not an element (e.g., text node, comment, etc.)
// For text nodes, output their data content
// Skip whitespace-only text nodes (OpenJade behavior)
if node.is_text() {
if let Some(text) = node.data() {
// Skip if text is only whitespace
if !text.trim().is_empty() {
// Output text to backend using literal() (each backend handles its own escaping)
if let Some(ref backend) = self.backend {
backend.borrow_mut().literal(&text)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
}
}
}
return Ok(Value::Unspecified);
}
};
// Find matching construction rule (in current processing mode)
let mode_name = self.current_processing_mode.clone();
let mode = self.mode_manager.get_mode(&mode_name);
let rule = mode.and_then(|m| m.find_match(&gi, &**node));
if let Some(rule) = rule {
// Rule found - evaluate the construction expression
// Save current source context
let saved_file = self.current_source_file.clone();
let saved_pos = self.current_position.clone();
// Restore source context to where the rule was defined
// This ensures error messages show the rule definition location, not the rule body location
if let Some(ref rule_file) = rule.source_file {
self.current_source_file = Some(rule_file.clone());
}
if let Some(ref rule_pos) = rule.source_pos {
self.current_position = Some(rule_pos.clone());
}
// Extract rule data to avoid borrow conflicts
let rule_expr = rule.expr.clone();
let rule_cached = rule.cached_instructions.clone();
// Evaluate the construction expression (with instruction caching if VM is enabled)
let result = if self.use_vm {
self.eval_rule_with_cache(rule_expr, rule_cached, env)
} else {
self.eval(rule_expr, env)
};
// Restore previous source context
self.current_source_file = saved_file;
self.current_position = saved_pos;
result
} else if let Some(default_expr) = mode.and_then(|m| m.default_rule.as_ref()).cloned() {
// No specific rule found - use default rule
self.eval(default_expr, env)
} else {
// No rule found (and no default) - OpenJade's implicit default behavior:
// Process children automatically (DSSSL §10.1.5)
self.eval_process_children(env)
}
}
/// Evaluate a construction rule with instruction caching (OpenJade's InsnPtr optimization)
///
/// This implements OpenJade's key performance optimization:
/// ```cpp
/// class Identifier {
/// Owner<Expression> def_; // Parsed AST
/// InsnPtr insn_; // Compiled instructions (cached!)
/// };
/// ```
///
/// Each construction rule compiles its expression ONCE and caches the bytecode.
/// Subsequent evaluations execute the cached instructions directly.
///
/// This is why OpenJade is 50-74x faster than tree-walking interpreters on
/// real DSSSL workloads (e.g., DocBook processing with thousands of rule applications).
fn eval_rule_with_cache(
&mut self,
rule_expr: Value,
rule_cached: RefCell<Option<(Vec<Instruction>, usize)>>,
_env: Gc<Environment>
) -> EvalResult {
// Check if we have cached instructions (clone to avoid holding the borrow)
let cached_data = rule_cached.borrow().clone();
if let Some((instructions, start_ip)) = cached_data {
// Cache hit! Execute cached instructions directly
// Create VM with primitives and extend with saved user-defined globals
let mut vm = VM::with_primitives(&mut self.arena);
vm.extend_globals(self.vm_globals.clone());
let result_id = vm.run(&instructions, start_ip)
.map_err(|e| EvalError::new(format!("VM error: {}", e)))?;
// Save globals for next execution
self.vm_globals = vm.get_user_globals();
// Debug: Log saved globals
if std::env::var("DAZZLE_DEBUG").is_ok() {
let saved: Vec<_> = self.vm_globals.keys().filter(|k| k.starts_with('%')).collect();
if !saved.is_empty() {
eprintln!("Evaluator: Saved {} user globals (% vars: {:?})", self.vm_globals.len(), saved);
}
}
// Convert back: ValueId → Value
return Ok(arena_to_value(&self.arena, result_id));
}
// Cache miss - compile and cache the instructions
let expr_id = value_to_arena(&mut self.arena, &rule_expr);
let mut compiler = Compiler::new(&self.arena);
let start_ip = compiler.compile(expr_id)
.map_err(|e| EvalError::new(format!("Compilation error: {}", e)))?;
let mut program = compiler.into_program();
program.emit(Instruction::Return);
// Cache the compiled instructions
let instructions = program.instructions.clone();
*rule_cached.borrow_mut() = Some((instructions.clone(), start_ip));
// Execute the newly compiled instructions
let mut vm = VM::with_primitives(&mut self.arena);
vm.extend_globals(self.vm_globals.clone());
let result_id = vm.run(&instructions, start_ip)
.map_err(|e| EvalError::new(format!("VM error: {}", e)))?;
// Save globals for next execution
self.vm_globals = vm.get_user_globals();
// Debug: Log saved globals
if std::env::var("DAZZLE_DEBUG").is_ok() {
let saved: Vec<_> = self.vm_globals.keys().filter(|k| k.starts_with('%')).collect();
if !saved.is_empty() {
eprintln!("Evaluator: Saved {} user globals (% vars: {:?})", self.vm_globals.len(), saved);
}
}
// Convert back: ValueId → Value
Ok(arena_to_value(&self.arena, result_id))
}
/// Evaluate an expression using the VM (bytecode execution)
///
/// This is OpenJade's optimization: compile expressions to bytecode once,
/// execute with a fast stack-based VM. Key advantages:
/// - No recursion (flat while loop)
/// - No pattern matching overhead
/// - Pre-resolved closures (no environment lookup)
/// - Stack-based (minimal GC pressure)
///
/// Returns Err if compilation or execution fails.
fn eval_with_vm(&mut self, expr: Value, _env: Gc<Environment>) -> EvalResult {
// Convert Value → ValueId (using bridge)
let expr_id = value_to_arena(&mut self.arena, &expr);
// Compile to bytecode
let mut compiler = Compiler::new(&self.arena);
let start_ip = compiler.compile(expr_id)
.map_err(|e| EvalError::new(format!("Compilation error: {}", e)))?;
let mut program = compiler.into_program();
// Add Return instruction at the end (top-level eval needs this)
program.emit(Instruction::Return);
// Create VM with primitives registered and extend with saved user-defined globals
let mut vm = VM::with_primitives(&mut self.arena);
vm.extend_globals(self.vm_globals.clone());
// Execute bytecode
let result_id = vm.run(&program.instructions, start_ip)
.map_err(|e| EvalError::new(format!("VM error: {}", e)))?;
// Save globals for next execution
self.vm_globals = vm.get_user_globals();
// Debug: Log saved globals
if std::env::var("DAZZLE_DEBUG").is_ok() {
let saved: Vec<_> = self.vm_globals.keys().filter(|k| k.starts_with('%')).collect();
if !saved.is_empty() {
eprintln!("Evaluator: Saved {} user globals (% vars: {:?})", self.vm_globals.len(), saved);
}
}
// Convert back: ValueId → Value
Ok(arena_to_value(&self.arena, result_id))
}
/// Temporarily disable VM mode (returns previous state)
///
/// This is useful for operations like template loading where VM mode's
/// arena allocation doesn't work well with intermediate values.
pub fn set_use_vm(&mut self, enabled: bool) -> bool {
let previous = self.use_vm;
self.use_vm = enabled;
previous
}
/// Sync all Environment definitions to vm_globals
///
/// This is needed when switching from tree-walker mode to VM mode.
/// Definitions made in tree-walker mode are stored in Environment (Gc),
/// but VM mode looks in vm_globals (HashMap<String, ValueId>).
pub fn sync_env_to_vm(&mut self, env: Gc<Environment>) -> Result<(), EvalError> {
use crate::scheme::bridge::value_to_arena;
// Get all bindings from environment
let bindings = env.all_bindings();
// Convert each binding to arena and store in vm_globals
for (name, value) in bindings {
let value_id = value_to_arena(&mut self.arena, &value);
self.vm_globals.insert(name, value_id);
}
Ok(())
}
/// Trigger garbage collection if needed
///
/// This should be called periodically during long-running operations like
/// template loading to prevent memory accumulation.
pub fn gc_if_needed(&mut self) {
// Collect Gc-wrapped values (tree-walker mode)
gc::force_collect();
// Collect arena values (VM mode)
// Preserve VM globals as GC roots
let roots: Vec<_> = self.vm_globals.values().copied().collect();
self.arena.gc(&roots);
}
/// Evaluate an expression in an environment
///
/// Corresponds to OpenJade's `Interpreter::eval()`.
///
/// ## Evaluation Rules
///
/// 1. **Self-evaluating**: Numbers, strings, bools, chars → return as-is
/// 2. **Symbols**: Variable lookup in environment
/// 3. **Lists**: Check first element for special forms, otherwise apply
pub fn eval(&mut self, expr: Value, env: Gc<Environment>) -> EvalResult {
// Check if VM execution is enabled
if self.use_vm {
return self.eval_with_vm(expr, env);
}
// Save previous context state
let context_was_set = has_evaluator_context();
let previous_context = get_evaluator_context();
// ALWAYS update context to reflect current evaluator state
// This ensures current_node is correct for nested eval() calls
set_evaluator_context(EvaluatorContext {
grove: self.arena.grove.clone(),
current_node: self.arena.current_node.clone(),
backend: self.backend.clone(),
});
// Evaluate
let result = self.eval_inner(expr, env);
// Restore previous context state
if context_was_set {
if let Some(prev_ctx) = previous_context {
set_evaluator_context(prev_ctx);
}
} else {
clear_evaluator_context();
}
result
}
/// Inner eval implementation (separated to ensure context cleanup)
fn eval_inner(&mut self, expr: Value, env: Gc<Environment>) -> EvalResult {
match expr {
// Self-evaluating literals
Value::Nil => Ok(Value::Nil),
Value::Bool(_) => Ok(expr),
Value::Integer(_) => Ok(expr),
Value::Real(_) => Ok(expr),
Value::Quantity { .. } => Ok(expr),
Value::Char(_) => Ok(expr),
Value::String(_) => Ok(expr),
Value::Procedure(_) => Ok(expr),
Value::Vector(_) => Ok(expr), // Vectors are self-evaluating in R4RS
Value::Unspecified => Ok(expr),
Value::Error => Ok(expr),
// DSSSL types (self-evaluating for now)
Value::Node(_) => Ok(expr),
Value::NodeList(_) => Ok(expr),
Value::Sosofo => Ok(expr),
// Symbols: variable lookup
Value::Symbol(ref name) => {
// First try environment lookup
if let Some(val) = env.lookup(name) {
return Ok(val);
}
// Fallback: check if this is a known primitive name
if let Some(static_name) = self.get_primitive_static_name(name) {
// Return a marker procedure that will be recognized during application
// Use a dummy function - the real dispatch happens in apply_primitive
return Ok(Value::primitive(static_name, |_args| {
Err("Primitive should be dispatched through apply_primitive".to_string())
}));
}
Err(self.error_with_stack(format!("Undefined variable: {}", name)))
},
// Keywords are self-evaluating
Value::Keyword(_) => Ok(expr),
// Lists: special forms or function application
Value::Pair(_) => self.eval_list(expr, env),
}
}
/// Evaluate a list (special form or function call)
fn eval_list(&mut self, expr: Value, env: Gc<Environment>) -> EvalResult {
// Extract position from the pair if available and update current position
if let Value::Pair(ref p) = expr {
let pair_data = p.borrow();
if let Some(ref pos) = pair_data.pos {
// If we have line mappings, translate the position to source file coordinates
if !self.line_mappings.is_empty() {
if let Some(mapping) = self.line_mappings.iter().find(|m| m.output_line == pos.line) {
self.current_source_file = Some(mapping.source_file.clone());
self.current_position = Some(Position {
line: mapping.source_line,
column: pos.column,
});
} else {
// No mapping found, use original position
self.current_position = Some(pos.clone());
}
} else {
// No line mappings, use original position
self.current_position = Some(pos.clone());
}
}
}
// Extract the operator (first element)
let (operator, args) = self.list_car_cdr(&expr)?;
// Check if operator is a symbol (special form keyword)
if let Value::Symbol(ref sym) = operator {
match &**sym {
"quote" => self.eval_quote(args),
"if" => self.eval_if(args, env),
"define" => self.eval_define(args, env),
"set!" => self.eval_set(args, env),
"lambda" => self.eval_lambda(args, env),
"let" => self.eval_let(args, env),
"let*" => self.eval_let_star(args, env),
"letrec" => self.eval_letrec(args, env),
"begin" => self.eval_begin(args, env),
"cond" => self.eval_cond(args, env),
"case" => self.eval_case(args, env),
"and" => self.eval_and(args, env),
"or" => self.eval_or(args, env),
"apply" => self.eval_apply(args, env),
"map" => self.eval_map(args, env),
"for-each" => self.eval_for_each(args, env),
"node-list-filter" => self.eval_node_list_filter(args, env),
"node-list-map" => self.eval_node_list_map(args, env),
"node-list-some?" => self.eval_node_list_some(args, env),
"load" => self.eval_load(args, env),
// DSSSL special forms
"define-unit" => self.eval_define_unit(args, env),
"define-language" => self.eval_define_language(args, env),
"declare-flow-object-class" => self.eval_declare_flow_object_class(args, env),
"declare-characteristic" => self.eval_declare_characteristic(args, env),
"declare-initial-value" => self.eval_declare_initial_value(args, env),
"mode" => self.eval_mode(args, env),
"with-mode" => self.eval_with_mode(args, env),
"element" => self.eval_element(args, env),
"default" => self.eval_default(args, env),
"process-children" => self.eval_process_children(env),
"process-children-trim" => self.eval_process_children_trim(env),
"process-node-list" => self.eval_process_node_list(args, env),
"make" => self.eval_make(args, env),
"style" => self.eval_style(args, env),
// Not a special form - evaluate as function call
_ => self.eval_application(operator, args, env),
}
} else {
// Operator is not a symbol - evaluate and apply
self.eval_application(operator, args, env)
}
}
/// Extract car and cdr from a list
fn list_car_cdr(&self, list: &Value) -> Result<(Value, Value), EvalError> {
if let Value::Pair(ref p) = list {
let pair = p.borrow();
Ok((pair.car.clone(), pair.cdr.clone()))
} else {
Err(EvalError::new("Expected list".to_string()))
}
}
/// Convert a Vec to a list
fn vec_to_list(&self, vec: Vec<Value>) -> Value {
let mut result = Value::Nil;
for val in vec.iter().rev() {
result = Value::cons(val.clone(), result);
}
result
}
/// Convert a list to a Vec of elements
pub fn list_to_vec(&self, list: Value) -> Result<Vec<Value>, EvalError> {
let mut result = Vec::new();
let mut current = list;
loop {
match current {
Value::Nil => break,
Value::Pair(ref p) => {
let pair = p.borrow();
result.push(pair.car.clone());
let cdr = pair.cdr.clone();
drop(pair); // Explicitly drop borrow before reassigning
current = cdr;
}
_ => return Err(EvalError::new("Improper list".to_string())),
}
}
Ok(result)
}
// =========================================================================
// Special Forms
// =========================================================================
/// (quote expr) → expr
fn eval_quote(&mut self, args: Value) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 1 {
return Err(EvalError::new("quote requires exactly 1 argument".to_string()));
}
Ok(args_vec[0].clone())
}
/// (if test consequent [alternate])
fn eval_if(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 || args_vec.len() > 3 {
return Err(EvalError::new(
"if requires 2 or 3 arguments".to_string(),
));
}
let test = self.eval_inner(args_vec[0].clone(), env.clone())?;
if test.is_true() {
self.eval_inner(args_vec[1].clone(), env)
} else if args_vec.len() == 3 {
self.eval_inner(args_vec[2].clone(), env)
} else {
Ok(Value::Unspecified)
}
}
/// (define name value) or (define (name params...) body...)
fn eval_define(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"define requires at least 2 arguments".to_string(),
));
}
// Check if first arg is a symbol or a list
match &args_vec[0] {
Value::Symbol(ref name) => {
// Simple variable definition: (define x value)
if args_vec.len() != 2 {
return Err(EvalError::new(
"define with symbol requires exactly 2 arguments".to_string(),
));
}
let value = self.eval_inner(args_vec[1].clone(), env.clone())?;
env.define(name, value);
Ok(Value::Unspecified)
}
Value::Pair(_) => {
// Function definition: (define (name params...) body...)
// This is syntactic sugar for: (define name (lambda (params...) body...))
let (name_val, params) = self.list_car_cdr(&args_vec[0])?;
if let Value::Symbol(ref name) = name_val {
// Parse parameters (handles #!optional)
let (param_names, required_count, optional_defaults) =
self.parse_lambda_params(params)?;
// Build body
let body = if args_vec.len() == 2 {
args_vec[1].clone()
} else {
let mut body_list = Value::Nil;
for expr in args_vec[1..].iter().rev() {
body_list = Value::cons(expr.clone(), body_list);
}
Value::cons(Value::symbol("begin"), body_list)
};
// Create lambda with function name and source info
let source_info = self.current_source_file.as_ref().map(|file| {
use crate::scheme::parser::Position;
SourceInfo::new(file.clone(), Position::new())
});
let lambda_value = if optional_defaults.is_empty() {
Value::lambda_with_source(
param_names,
body,
env.clone(),
source_info,
Some(name.to_string()),
)
} else {
Value::lambda_with_optional(
param_names,
required_count,
optional_defaults,
body,
env.clone(),
source_info,
Some(name.to_string()),
)
};
env.define(name, lambda_value);
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First element of define must be a symbol".to_string(),
))
}
}
_ => Err(EvalError::new(
"First argument to define must be symbol or list".to_string(),
)),
}
}
/// Evaluate (define-unit name value)
/// DSSSL unit definition - defines a unit (em, pi, pt, etc.) as a quantity value
/// Examples:
/// (define-unit em %bf-size%)
/// (define-unit pi (/ 1in 6))
fn eval_define_unit(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new(
"define-unit requires exactly 2 arguments: name and value".to_string(),
));
}
// First argument must be a symbol (unit name)
if let Value::Symbol(ref name) = args_vec[0] {
// Evaluate the value expression
let value = self.eval_inner(args_vec[1].clone(), env.clone())?;
// Define the unit name in the environment
env.define(name, value);
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to define-unit must be a symbol".to_string(),
))
}
}
/// Evaluate (define-language name props...)
/// DSSSL language definition - defines the language name as a symbol
fn eval_define_language(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(EvalError::new(
"define-language requires at least 1 argument".to_string(),
));
}
// First argument must be a symbol (language name)
if let Value::Symbol(ref name) = args_vec[0] {
// Define the language name as a symbol bound to itself
// This allows it to be used in (declare-default-language name)
env.define(name, args_vec[0].clone());
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to define-language must be a symbol".to_string(),
))
}
}
/// Evaluate (declare-flow-object-class name public-id)
/// DSSSL flow object class declaration - defines the class name as a symbol
fn eval_declare_flow_object_class(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(EvalError::new(
"declare-flow-object-class requires at least 1 argument".to_string(),
));
}
// First argument must be a symbol (flow object class name)
if let Value::Symbol(ref name) = args_vec[0] {
// Define the class name as a symbol bound to itself
// This allows it to be used in (make name ...) constructs
env.define(name, args_vec[0].clone());
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to declare-flow-object-class must be a symbol".to_string(),
))
}
}
/// Evaluate (declare-characteristic name public-id default-value)
/// DSSSL characteristic declaration - defines the characteristic with its default value
fn eval_declare_characteristic(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 3 {
return Err(EvalError::new(
"declare-characteristic requires at least 3 arguments (name, public-id, default-value)".to_string(),
));
}
// First argument must be a symbol (characteristic name)
if let Value::Symbol(ref name) = args_vec[0] {
// Third argument is the default value - evaluate it
let default_value = self.eval(args_vec[2].clone(), env.clone())?;
// Define the characteristic name as a variable with its default value
env.define(name, default_value);
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to declare-characteristic must be a symbol".to_string(),
))
}
}
/// Evaluate (declare-initial-value name value)
/// DSSSL initial value declaration - sets the initial value for a characteristic
/// Example: (declare-initial-value page-width 210mm)
fn eval_declare_initial_value(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new(
"declare-initial-value requires exactly 2 arguments (name and value)".to_string(),
));
}
// First argument must be a symbol (characteristic name)
if let Value::Symbol(ref name) = args_vec[0] {
// Second argument is the value - evaluate it
let value = self.eval_inner(args_vec[1].clone(), env.clone())?;
// Define the characteristic name as a variable with its value
env.define(name, value);
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to declare-initial-value must be a symbol".to_string(),
))
}
}
/// DSSSL element construction rule (OpenJade SchemeParser::doElement)
/// Syntax: (element element-pattern construction-expression)
///
/// Element pattern can be:
/// - A symbol: (element foo ...)
/// - A list for context matching: (element (parent child) ...)
///
/// Stores the rule in processing mode WITHOUT evaluating the body.
/// The body will be evaluated later during tree processing when a matching element is found.
fn eval_element(&mut self, args: Value, _env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(self.error_with_stack(
"element requires at least 2 arguments (element-pattern and construction-expression)".to_string(),
));
}
// First argument is the element pattern (symbol or list)
// For context matching like (parent child), extract the last element and context
let (element_name, context) = match &args_vec[0] {
Value::Symbol(ref name) => (name.clone(), Vec::new()),
Value::Pair(_) => {
// List pattern like (parent child) - extract context and element
let pattern_list = self.list_to_vec(args_vec[0].clone())?;
if pattern_list.is_empty() {
return Err(self.error_with_stack(
"Element pattern list cannot be empty".to_string(),
));
}
// Last element in the list is the actual element being matched
let element_name = if let Value::Symbol(ref name) = pattern_list[pattern_list.len() - 1] {
name.clone()
} else {
return Err(self.error_with_stack(
"Element pattern must contain only symbols".to_string(),
));
};
// Elements before the last one are the context (parent chain)
let mut context = Vec::new();
for i in 0..pattern_list.len() - 1 {
if let Value::Symbol(ref parent_name) = pattern_list[i] {
context.push(parent_name.to_string());
} else {
return Err(self.error_with_stack(
"Element pattern must contain only symbols".to_string(),
));
}
}
(element_name, context)
}
_ => {
return Err(self.error_with_stack(
"First argument to element must be a symbol or list of symbols".to_string(),
));
}
};
// Remaining arguments are the construction expressions
// OpenJade behavior: error on multiple expressions for better error detection
// (suggest using sosofo-append explicitly)
if args_vec.len() > 2 {
return Err(self.error_with_stack(
"element can only contain one sosofo expression. Use (sosofo-append ...) to combine multiple sosofos".to_string(),
));
}
let construction_expr = args_vec[1].clone();
// Store the construction expression for later evaluation
// Capture the current source position (where the 'element' form is)
// Add the rule to the current mode
let mode_name = self.current_mode.clone();
self.mode_manager.get_or_create_mode(&mode_name).add_rule(
element_name.to_string(),
context,
construction_expr,
self.current_source_file.clone(),
self.current_position.clone()
);
Ok(Value::Unspecified)
}
/// DSSSL default construction rule
/// Syntax: (default construction-expression)
///
/// Defines a default rule that applies to all elements that don't have a specific rule.
/// This is the catch-all rule.
fn eval_default(&mut self, args: Value, _env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(self.error_with_stack(
"default requires at least 1 argument (construction-expression)".to_string(),
));
}
// OpenJade behavior: error on multiple expressions for better error detection
// (suggest using sosofo-append explicitly)
if args_vec.len() > 1 {
return Err(self.error_with_stack(
"default can only contain one sosofo expression. Use (sosofo-append ...) to combine multiple sosofos".to_string(),
));
}
let construction_expr = args_vec[0].clone();
// Store the default rule in the current mode
let mode_name = self.current_mode.clone();
self.mode_manager.get_or_create_mode(&mode_name).add_default_rule(construction_expr);
Ok(Value::Unspecified)
}
/// DSSSL mode definition
/// Syntax: (mode mode-name rule1 rule2 ...)
///
/// Defines a named processing mode with its own construction rules.
/// All element and default rules within the mode body are added to the specified mode.
fn eval_mode(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(self.error_with_stack(
"mode requires at least 1 argument (mode-name)".to_string(),
));
}
// First argument is the mode name (symbol)
let mode_name = if let Value::Symbol(ref name) = args_vec[0] {
name.clone()
} else {
return Err(self.error_with_stack(
"First argument to mode must be a symbol".to_string(),
));
};
// Save the current mode
let saved_mode = self.current_mode.clone();
// Switch to the new mode
self.current_mode = mode_name.to_string();
// Evaluate all the body expressions (element/default definitions)
let mut result = Value::Unspecified;
for expr in args_vec.iter().skip(1) {
result = self.eval(expr.clone(), env.clone())?;
}
// Restore the previous mode
self.current_mode = saved_mode;
Ok(result)
}
/// DSSSL with-mode - temporarily switch processing mode
/// Syntax: (with-mode mode-name expr)
///
/// Evaluates expr with the processing mode temporarily switched to mode-name.
/// Rules are looked up in the specified mode during processing.
fn eval_with_mode(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(self.error_with_stack(
"with-mode requires 2 arguments (mode-name and expression)".to_string(),
));
}
// First argument is the mode name (symbol)
let mode_name = if let Value::Symbol(ref name) = args_vec[0] {
name.clone()
} else {
return Err(self.error_with_stack(
"First argument to with-mode must be a symbol".to_string(),
));
};
// Save the current processing mode
let saved_processing_mode = self.current_processing_mode.clone();
// Switch to the new processing mode
self.current_processing_mode = mode_name.to_string();
// Evaluate the expression in the new mode
let result = self.eval(args_vec[1].clone(), env);
// Restore the previous processing mode
self.current_processing_mode = saved_processing_mode;
result
}
/// DSSSL process-children (OpenJade ProcessContext::processChildren)
/// Syntax: (process-children)
///
/// Processes all children of the current node.
/// For each child, matches construction rules and evaluates them.
fn eval_process_children(&mut self, env: Gc<Environment>) -> EvalResult {
// Get current node
let current_node = match self.current_node() {
Some(node) => node.clone(),
None => return Err(EvalError::new("No current node".to_string())),
};
// Get ALL children (including text nodes)
// Note: all_children() returns elements AND text, not just elements like children()
let mut children = current_node.all_children();
// Process each child (using DSSSL node-list iteration pattern)
let mut result = Value::Unspecified;
while !children.is_empty() {
// Get first child
if let Some(child_node) = children.first() {
// Save current node
let saved_node = self.current_node();
// Set child as current node
self.set_current_node(child_node);
// Process the child node
result = self.process_node(env.clone())?;
// Restore current node
self.restore_current_node(saved_node);
}
// Move to rest of children
children = children.rest();
}
Ok(result)
}
/// DSSSL (process-children-trim)
///
/// OpenJade semantics: Process children with whitespace trimming
/// - Text nodes are output directly to backend (not through rules)
/// - Leading whitespace is trimmed from first text node
/// - Trailing whitespace is trimmed from last text node
/// - Element nodes are processed through rules normally
fn eval_process_children_trim(&mut self, env: Gc<Environment>) -> EvalResult {
// Get current node
let current_node = match self.current_node() {
Some(node) => node.clone(),
None => return Err(EvalError::new("No current node".to_string())),
};
// Get ALL children (including text nodes)
let mut children = current_node.all_children();
// Collect all children into a vector to support trimming
let mut child_nodes = Vec::new();
while !children.is_empty() {
if let Some(child) = children.first() {
child_nodes.push(child);
}
children = children.rest();
}
if child_nodes.is_empty() {
return Ok(Value::Unspecified);
}
// Track position for trimming
let mut at_start = true;
// Process each child
for (index, child_node) in child_nodes.iter().enumerate() {
let is_last = index == child_nodes.len() - 1;
if child_node.is_text() {
// Text node: output directly with trimming
if let Some(mut text) = child_node.data() {
// Trim leading whitespace from first text node
if at_start {
let trimmed = text.trim_start();
if trimmed.is_empty() {
// Skip whitespace-only nodes at start
continue;
}
text = trimmed.to_string();
at_start = false;
}
// Trim trailing whitespace from last text node
if is_last {
text = text.trim_end().to_string();
}
if !text.is_empty() {
// Output text directly to backend
if let Some(ref backend) = self.backend {
backend.borrow_mut().literal(&text)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
}
}
} else if child_node.is_element() {
// Element node: mark that we're no longer at start
at_start = false;
// Process through rules
let saved_node = self.current_node();
self.set_current_node(child_node.clone_node());
let _result = self.process_node(env.clone())?;
self.restore_current_node(saved_node);
}
}
Ok(Value::Unspecified)
}
/// DSSSL (process-node-list node-list)
/// Syntax: (process-node-list node-list)
///
/// Processes all nodes in the given node-list.
/// For each node, matches construction rules and evaluates them.
fn eval_process_node_list(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 1 {
return Err(EvalError::new(
"process-node-list requires exactly 1 argument".to_string(),
));
}
// Evaluate the argument to get the node-list
let node_list_value = self.eval(args_vec[0].clone(), env.clone())?;
// Get the node-list (auto-convert single node to singleton node-list)
let mut nodes = match node_list_value {
Value::NodeList(ref nl) => nl.clone(),
Value::Node(ref n) => {
// Auto-convert single node to singleton node-list
// n is Rc<Box<dyn Node>>, we need Vec<Box<dyn Node>>
let node_box: Box<dyn crate::grove::Node> = (**n).clone_node();
Rc::new(Box::new(crate::grove::VecNodeList::new(vec![node_box])) as Box<dyn crate::grove::NodeList>)
}
_ => {
return Err(EvalError::new(format!(
"process-node-list: not a node-list: {:?}",
node_list_value
)))
}
};
// Process each node (using DSSSL node-list iteration pattern)
let mut result = Value::Unspecified;
while !nodes.is_empty() {
// Get first node
if let Some(node) = nodes.first() {
// Save current node
let saved_node = self.current_node();
// Set this node as current node
self.set_current_node(node);
// Process the node
result = self.process_node(env.clone())?;
// Restore current node
self.restore_current_node(saved_node);
}
// Move to rest of nodes
nodes = Rc::new(nodes.rest());
}
Ok(result)
}
/// DSSSL make flow object (OpenJade FotBuilder)
/// Syntax: (make flow-object-type keyword: value ... body-sosofo)
///
/// Creates flow objects and writes them to the backend.
/// Supports: entity, formatting-instruction
fn eval_make(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(EvalError::new(
"make requires at least a flow object type".to_string(),
));
}
// First argument is the flow object type (symbol)
let fo_type = match &args_vec[0] {
Value::Symbol(s) => s.as_ref(),
_ => return Err(EvalError::new(
"make: first argument must be a flow object type symbol".to_string(),
)),
};
// Parse keyword arguments and collect body expressions
let mut i = 1;
let mut system_id = None;
let mut data = None;
let mut path = None;
let mut gi = None;
let mut attributes = None;
let mut body_exprs = Vec::new();
while i < args_vec.len() {
match &args_vec[i] {
Value::Keyword(kw) => {
// Next argument is the keyword value
if i + 1 >= args_vec.len() {
return Err(EvalError::new(
format!("make: keyword {} requires a value", kw),
));
}
// Debug: Log keyword processing
if std::env::var("DAZZLE_DEBUG").is_ok() {
eprintln!("EVAL_MAKE: Processing keyword '{}:', value expr = {:?}",
kw, args_vec[i + 1]);
}
let value = self.eval(args_vec[i + 1].clone(), env.clone())?;
// Debug: Log evaluated value
if std::env::var("DAZZLE_DEBUG").is_ok() {
eprintln!("EVAL_MAKE: Keyword '{}' evaluated to {:?}", kw, value);
}
match kw.as_ref() {
"system-id" => {
if let Value::String(s) = value {
system_id = Some(s);
} else {
return Err(EvalError::new(
"make: system-id must be a string".to_string(),
));
}
}
"data" => {
if let Value::String(s) = value {
data = Some(s);
} else {
return Err(EvalError::new(
format!("make: data must be a string, got {:?}", value),
));
}
}
"path" => {
if let Value::String(s) = value {
path = Some(s);
} else {
return Err(EvalError::new(
"make: path must be a string".to_string(),
));
}
}
"gi" => {
if let Value::String(s) = value {
gi = Some(s);
} else {
return Err(EvalError::new(
"make element: gi must be a string".to_string(),
));
}
}
"attributes" => {
// attributes can be a list or #f
attributes = Some(value);
}
_ => {
// Ignore unknown keywords for now
}
}
i += 2;
}
_ => {
// Non-keyword argument - collect as body expression
body_exprs.push(args_vec[i].clone());
i += 1;
}
}
}
// Call backend method based on flow object type
let backend = self.backend.clone();
match backend {
Some(ref backend) => {
match fo_type {
"entity" => {
if let Some(sid) = system_id {
// Save current buffer (for nested entities)
let saved_buffer = backend.borrow().current_output().to_string();
backend.borrow_mut().clear_buffer();
// Evaluate body expressions (they append to buffer)
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
// Get current buffer content and write to file
let content = backend.borrow().current_output().to_string();
backend.borrow_mut().entity(&sid, &content)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
// Restore saved buffer (for parent entity context)
backend.borrow_mut().clear_buffer();
backend.borrow_mut().formatting_instruction(&saved_buffer)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
} else {
return Err(EvalError::new(
"make entity requires system-id: keyword".to_string(),
));
}
}
"formatting-instruction" => {
if let Some(d) = data {
// Append to current buffer
backend.borrow_mut().formatting_instruction(&d)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
} else {
return Err(EvalError::new(
"make formatting-instruction requires data: keyword".to_string(),
));
}
}
"literal" => {
// literal is typically called as (literal "text") not (make literal ...)
// but we support both forms for completeness
if let Some(d) = data {
backend.borrow_mut().formatting_instruction(&d)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
} else {
return Err(EvalError::new(
"make literal requires data: keyword or a string body".to_string(),
));
}
}
"directory" => {
if let Some(p) = path {
// Save current directory context
let prev_dir = backend.borrow().current_directory().map(|s| s.to_string());
// Create directory and set as current context
backend.borrow_mut().directory(&p)
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
// Evaluate body expressions in the new directory context
// (nested entities/directories will be created relative to this directory)
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
// Restore previous directory context
backend.borrow_mut().set_current_directory(prev_dir);
} else {
return Err(EvalError::new(
"make directory requires path: keyword".to_string(),
));
}
}
"sequence" => {
// Sequence evaluates all body expressions in order
// This is the primary composition mechanism for flow objects
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
}
"element" => {
// OpenJade extension: (make element gi: "name" attributes: '(("key" "val")) body...)
// Outputs: <name\nkey="val"\n>body</name\n>
//
// This is a compound flow object that generates HTML-like tags
// with OpenJade's special formatting (newline after tag name and each attribute)
let gi = gi.ok_or_else(|| EvalError::new(
"make element requires gi: keyword".to_string()
))?;
// Start tag with newline after tag name
backend.borrow_mut().formatting_instruction(&format!("<{}\n", gi))
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
// Add attributes if present, each on its own line
if let Some(attrs_val) = attributes {
// attributes should be a list of (name value) pairs
let attrs_list = self.list_to_vec(attrs_val)?;
for attr_pair in attrs_list {
let pair_vec = self.list_to_vec(attr_pair)?;
if pair_vec.len() == 2 {
if let (Value::String(name), Value::String(value)) =
(&pair_vec[0], &pair_vec[1]) {
// Escape special characters in attribute value
let escaped_value = value
.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">");
backend.borrow_mut().formatting_instruction(&format!("{}=\"{}\"\n", name, escaped_value))
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
}
}
}
// Closing > for opening tag
backend.borrow_mut().formatting_instruction(">")
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
// Evaluate body expressions
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
// End tag with OpenJade's line break pattern
backend.borrow_mut().formatting_instruction(&format!("</{}\n>", gi))
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
"paragraph" => {
// RTF paragraph flow object
// Start paragraph
backend.borrow_mut().start_paragraph()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
// Evaluate body expressions (literal text, etc.)
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
// End paragraph
backend.borrow_mut().end_paragraph()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
"display-group" => {
// RTF display-group flow object
backend.borrow_mut().start_display_group()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
backend.borrow_mut().end_display_group()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
"simple-page-sequence" => {
// RTF simple-page-sequence flow object (main page container)
backend.borrow_mut().start_simple_page_sequence()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
backend.borrow_mut().end_simple_page_sequence()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
"line-field" => {
// RTF line-field flow object (inline text container)
backend.borrow_mut().start_line_field()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
backend.borrow_mut().end_line_field()
.map_err(|e| EvalError::new(format!("Backend error: {}", e)))?;
}
"link" | "scroll" | "marginalia" | "leader" | "table" | "table-row" | "table-cell" | "table-column" | "table-part" | "paragraph-break" => {
// Flow objects that just process their children
// For SGML backend (code gen), we ignore these formatting constructs
for expr in body_exprs {
self.eval(expr, env.clone())?;
}
}
_ => {
// Unknown flow object type - error
return Err(EvalError::new(
format!("make: unknown flow object type '{}'", fo_type),
));
}
}
}
None => {
return Err(EvalError::new(
"make: no backend available".to_string(),
));
}
}
// Flow objects (make forms) always return a Sosofo
Ok(Value::Sosofo)
}
/// (style keyword: value ...)
///
/// Stub for DSSSL style objects used in document formatting.
/// Dazzle focuses on code generation, so this returns a dummy value.
fn eval_style(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
// Parse keyword arguments (but ignore them)
let args_vec = self.list_to_vec(args)?;
let mut i = 0;
while i < args_vec.len() {
match &args_vec[i] {
Value::Keyword(_kw) => {
// Skip keyword and its value
if i + 1 >= args_vec.len() {
return Err(EvalError::new(
"style: keyword requires a value".to_string(),
));
}
// Evaluate the value (to check for errors) but don't use it
let _value = self.eval(args_vec[i + 1].clone(), env.clone())?;
i += 2;
}
_ => {
return Err(EvalError::new(
format!("style: unexpected argument {:?}", args_vec[i]),
));
}
}
}
// Return a dummy style object (we don't use it for code generation)
Ok(Value::Symbol(Rc::from("dummy-style")))
}
/// (set! name value)
fn eval_set(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new(
"set! requires exactly 2 arguments".to_string(),
));
}
if let Value::Symbol(ref name) = args_vec[0] {
let value = self.eval(args_vec[1].clone(), env.clone())?;
env.set(name, value)
.map_err(|e| EvalError::new(e))?;
Ok(Value::Unspecified)
} else {
Err(EvalError::new(
"First argument to set! must be a symbol".to_string(),
))
}
}
/// (lambda (params...) body...)
fn eval_lambda(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"lambda requires at least 2 arguments (params and body)".to_string(),
));
}
// Parse parameter list (handles #!optional parameters)
let params_list = &args_vec[0];
let (param_names, required_count, optional_defaults) =
self.parse_lambda_params(params_list.clone())?;
// Extract body (one or more expressions)
let body = if args_vec.len() == 2 {
// Single body expression
args_vec[1].clone()
} else {
// Multiple body expressions - wrap in (begin ...)
let mut body_list = Value::Nil;
for expr in args_vec[1..].iter().rev() {
body_list = Value::cons(expr.clone(), body_list);
}
Value::cons(Value::symbol("begin"), body_list)
};
// Create lambda closure capturing current environment and source location
// current_position has been set by eval_list to the position of the (lambda ...) expression
let source_info = match (&self.current_source_file, &self.current_position) {
(Some(file), Some(pos)) => {
// Clone the position since we'll be mutating current_position later
Some(SourceInfo::new(file.clone(), pos.clone()))
}
(Some(file), None) => {
use crate::scheme::parser::Position;
Some(SourceInfo::new(file.clone(), Position::new()))
}
_ => None,
};
// Create lambda with optional parameters if present
if optional_defaults.is_empty() {
Ok(Value::lambda_with_source(param_names, body, env, source_info, None))
} else {
Ok(Value::lambda_with_optional(
param_names,
required_count,
optional_defaults,
body,
env,
source_info,
None,
))
}
}
/// Parse lambda parameter list, handling #!optional parameters
///
/// Returns: (param_names, required_count, optional_defaults)
fn parse_lambda_params(
&mut self,
params: Value,
) -> Result<(Vec<String>, usize, Vec<Value>), EvalError> {
if params.is_nil() {
return Ok((Vec::new(), 0, Vec::new()));
}
let params_vec = self.list_to_vec(params)?;
let mut param_names = Vec::new();
let mut required_count = 0;
let mut optional_defaults = Vec::new();
let mut in_optional = false;
for param in params_vec {
// Check for #!optional marker
if let Value::Symbol(ref sym) = param {
if sym.as_ref() == "#!optional" {
in_optional = true;
continue;
}
}
if !in_optional {
// Required parameter - must be a symbol
if let Value::Symbol(ref name) = param {
param_names.push(name.to_string());
required_count += 1;
} else {
return Err(EvalError::new(format!(
"Parameter must be a symbol, got: {:?}",
param
)));
}
} else {
// Optional parameter - can be symbol or (symbol default)
match param {
Value::Symbol(ref name) => {
// Optional with no default: use #<unspecified>
param_names.push(name.to_string());
optional_defaults.push(Value::Unspecified);
}
Value::Pair(_) => {
// (name default-expr)
let opt_list = self.list_to_vec(param)?;
if opt_list.len() != 2 {
return Err(EvalError::new(format!(
"Optional parameter must be (name default), got list of length {}",
opt_list.len()
)));
}
if let Value::Symbol(ref name) = opt_list[0] {
param_names.push(name.to_string());
// Store the unevaluated default expression
if std::env::var("DEBUG_OPTIONAL").is_ok() {
eprintln!("[DEBUG_OPTIONAL] Storing default for param '{}': {:?}", name, opt_list[1]);
}
optional_defaults.push(opt_list[1].clone());
} else {
return Err(EvalError::new(format!(
"Optional parameter name must be a symbol, got: {:?}",
opt_list[0]
)));
}
}
_ => {
return Err(EvalError::new(format!(
"Optional parameter must be symbol or (symbol default), got: {:?}",
param
)));
}
}
}
}
Ok((param_names, required_count, optional_defaults))
}
/// (let ((var val)...) body...)
fn eval_let(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"let requires at least 2 arguments".to_string(),
));
}
// Check if this is named let: (let name ((var val)...) body...)
if let Value::Symbol(ref loop_name) = args_vec[0] {
if args_vec.len() < 3 {
return Err(EvalError::new(
"named let requires at least 3 arguments".to_string(),
));
}
// Named let: transform to (letrec ((name (lambda (vars...) body...))) (name vals...))
let bindings_list = &args_vec[1];
let bindings = self.list_to_vec(bindings_list.clone())?;
let body = &args_vec[2..];
// Extract variable names and initial values
let mut var_names = Vec::new();
let mut init_values = Vec::new();
for binding in &bindings {
let binding_vec = self.list_to_vec(binding.clone())?;
if binding_vec.len() != 2 {
return Err(EvalError::new(
"named let binding must have exactly 2 elements".to_string(),
));
}
var_names.push(binding_vec[0].clone());
init_values.push(binding_vec[1].clone());
}
// Create lambda: (lambda (vars...) body...)
let lambda_params = self.vec_to_list(var_names);
let mut lambda_body = vec![Value::symbol("lambda"), lambda_params];
lambda_body.extend_from_slice(body);
let lambda_expr = self.vec_to_list(lambda_body);
// Create letrec binding: ((name (lambda ...)))
let letrec_binding = Value::cons(
Value::symbol(loop_name),
Value::cons(lambda_expr, Value::Nil),
);
let letrec_bindings = Value::cons(letrec_binding, Value::Nil);
// Create function call: (name vals...)
let mut call_expr = vec![Value::symbol(loop_name)];
call_expr.extend_from_slice(&init_values);
let call = self.vec_to_list(call_expr);
// Evaluate: (letrec ((name (lambda ...))) (name vals...))
return self.eval_letrec(self.vec_to_list(vec![letrec_bindings, call]), env);
}
// Standard let: (let ((var val)...) body...)
let bindings_list = &args_vec[0];
let bindings = self.list_to_vec(bindings_list.clone())?;
// Create new environment extending current
let new_env = Environment::extend(env.clone());
// Evaluate bindings in OLD environment, define in NEW environment
for binding in bindings {
let binding_vec = self.list_to_vec(binding)?;
if binding_vec.len() != 2 {
return Err(EvalError::new(
"let binding must have exactly 2 elements".to_string(),
));
}
if let Value::Symbol(ref name) = binding_vec[0] {
let value = self.eval_inner(binding_vec[1].clone(), env.clone())?;
new_env.define(name, value);
} else {
return Err(EvalError::new(
"Binding variable must be a symbol".to_string(),
));
}
}
// Evaluate body in new environment
let body = &args_vec[1..];
self.eval_sequence(body, new_env)
}
/// (let* ((var val)...) body...)
fn eval_let_star(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"let* requires at least 2 arguments".to_string(),
));
}
// Parse bindings
let bindings_list = &args_vec[0];
let bindings = self.list_to_vec(bindings_list.clone())?;
// Create new environment
let current_env = Environment::extend(env);
// Evaluate bindings sequentially in CURRENT environment
for binding in bindings {
let binding_vec = self.list_to_vec(binding)?;
if binding_vec.len() != 2 {
return Err(EvalError::new(
"let* binding must have exactly 2 elements".to_string(),
));
}
if let Value::Symbol(ref name) = binding_vec[0] {
let value = self.eval_inner(binding_vec[1].clone(), current_env.clone())?;
current_env.define(name, value);
} else {
return Err(EvalError::new(
"Binding variable must be a symbol".to_string(),
));
}
}
// Evaluate body
let body = &args_vec[1..];
self.eval_sequence(body, current_env)
}
/// (letrec ((var val)...) body...)
///
/// letrec allows recursive definitions - all bindings can refer to each other.
/// Implementation:
/// 1. Create new environment
/// 2. Bind all variables to Unspecified first
/// 3. Evaluate all values in the new environment
/// 4. Update bindings with evaluated values
/// 5. Evaluate body in the new environment
fn eval_letrec(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"letrec requires at least 2 arguments".to_string(),
));
}
// Parse bindings
let bindings_list = &args_vec[0];
let bindings = self.list_to_vec(bindings_list.clone())?;
// Create new environment extending current
let new_env = Environment::extend(env);
// First pass: bind all variables to Unspecified
let mut var_names = Vec::new();
for binding in &bindings {
let binding_vec = self.list_to_vec(binding.clone())?;
if binding_vec.len() != 2 {
return Err(EvalError::new(
"letrec binding must have exactly 2 elements".to_string(),
));
}
if let Value::Symbol(ref name) = binding_vec[0] {
var_names.push(name.to_string());
new_env.define(name, Value::Unspecified);
} else {
return Err(EvalError::new(
"Binding variable must be a symbol".to_string(),
));
}
}
// Second pass: evaluate all values in the new environment and update bindings
for (i, binding) in bindings.iter().enumerate() {
let binding_vec = self.list_to_vec(binding.clone())?;
let value = self.eval_inner(binding_vec[1].clone(), new_env.clone())?;
// Update the binding (set! will work since we already defined it)
new_env.set(&var_names[i], value)
.map_err(|e| EvalError::new(e))?;
}
// Evaluate body in new environment
let body = &args_vec[1..];
self.eval_sequence(body, new_env)
}
/// (begin expr...)
fn eval_begin(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
self.eval_sequence(&args_vec, env)
}
/// (cond (test expr...)...)
fn eval_cond(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let clauses = self.list_to_vec(args)?;
for clause in clauses {
let clause_vec = self.list_to_vec(clause)?;
if clause_vec.is_empty() {
return Err(EvalError::new("Empty cond clause".to_string()));
}
// Check for else clause
if let Value::Symbol(ref sym) = clause_vec[0] {
if &**sym == "else" {
return self.eval_sequence(&clause_vec[1..], env);
}
}
// Evaluate test
let test = self.eval_inner(clause_vec[0].clone(), env.clone())?;
if test.is_true() {
if clause_vec.len() == 1 {
return Ok(test);
} else {
return self.eval_sequence(&clause_vec[1..], env);
}
}
}
Ok(Value::Unspecified)
}
/// (case key ((datum...) expr...)...)
///
/// R4RS case statement:
/// ```scheme
/// (case expr
/// ((datum1 datum2 ...) result1 result2 ...)
/// ((datum3 datum4 ...) result3 result4 ...)
/// ...
/// [else resultN ...])
/// ```
///
/// The key expression is evaluated and compared with each datum using eqv?.
/// The datums are NOT evaluated (they are literal constants).
fn eval_case(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Err(EvalError::new("case requires at least 1 argument".to_string()));
}
// Evaluate the key expression
let key = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Iterate through clauses
for clause in &args_vec[1..] {
let clause_vec = self.list_to_vec(clause.clone())?;
if clause_vec.is_empty() {
return Err(EvalError::new("Empty case clause".to_string()));
}
// Check for else clause
if let Value::Symbol(ref sym) = clause_vec[0] {
if &**sym == "else" {
return self.eval_sequence(&clause_vec[1..], env);
}
}
// First element should be a list of datums
let datums = self.list_to_vec(clause_vec[0].clone())?;
// Check if key matches any datum using equal? (not eqv?)
// NOTE: R4RS specifies eqv?, but that doesn't work for strings.
// OpenJade uses equal? for case matching to handle string comparisons.
for datum in datums {
if key.equal(&datum) {
// Match found - evaluate body expressions
if clause_vec.len() == 1 {
// No expressions in clause - return unspecified
return Ok(Value::Unspecified);
} else {
return self.eval_sequence(&clause_vec[1..], env);
}
}
}
}
// No match found - OpenJade treats this as an error for better error detection
// R4RS says result is unspecified, but OpenJade's behavior is more useful
Err(EvalError::new("case: no matching clause and no else clause".to_string()))
}
/// (and expr...)
fn eval_and(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.is_empty() {
return Ok(Value::bool(true));
}
let mut result = Value::bool(true);
for expr in args_vec {
result = self.eval_inner(expr, env.clone())?;
if !result.is_true() {
return Ok(Value::bool(false));
}
}
Ok(result)
}
/// (or expr...)
fn eval_or(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
for expr in args_vec {
let result = self.eval_inner(expr, env.clone())?;
if result.is_true() {
return Ok(result);
}
}
Ok(Value::bool(false))
}
/// Evaluate a sequence of expressions, return last result
fn eval_sequence(&mut self, exprs: &[Value], env: Gc<Environment>) -> EvalResult {
if exprs.is_empty() {
return Ok(Value::Unspecified);
}
let mut result = Value::Unspecified;
for expr in exprs {
result = self.eval_inner(expr.clone(), env.clone())?;
}
Ok(result)
}
/// (apply proc args)
///
/// Apply a procedure to a list of arguments.
/// Example: (apply + '(1 2 3)) → 6
fn eval_apply(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new(
"apply requires exactly 2 arguments".to_string(),
));
}
// Evaluate the procedure
let proc = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate the argument list
let arg_list = self.eval_inner(args_vec[1].clone(), env)?;
// Convert argument list to vector
let arg_values = self.list_to_vec(arg_list)?;
// Apply the procedure
self.apply(proc, arg_values)
}
/// (map proc list)
///
/// Apply procedure to each element of list, return list of results.
/// Example: (map (lambda (x) (* x 2)) '(1 2 3)) → '(2 4 6)
/// (map proc list1 list2 ...)
///
/// R4RS: Apply procedure to corresponding elements of lists.
/// All lists must have the same length.
/// Returns a list of results.
///
/// Examples:
/// - (map + '(1 2 3) '(4 5 6)) => (5 7 9)
/// - (map list '(1 2) '(a b) '(x y)) => ((1 a x) (2 b y))
fn eval_map(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new("map requires at least 2 arguments".to_string()));
}
// Evaluate the procedure
let proc = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate all lists
let mut lists = Vec::new();
for i in 1..args_vec.len() {
let list = self.eval_inner(args_vec[i].clone(), env.clone())?;
let list_vec = self.list_to_vec(list)?;
lists.push(list_vec);
}
// Check all lists have the same length
if lists.is_empty() {
return Ok(Value::Nil);
}
let length = lists[0].len();
for list in &lists[1..] {
if list.len() != length {
return Err(EvalError::new(
"map: all lists must have the same length".to_string(),
));
}
}
// Apply procedure to corresponding elements
let mut result_vec = Vec::new();
for i in 0..length {
// Gather i-th element from each list
let mut proc_args = Vec::new();
for list in &lists {
proc_args.push(list[i].clone());
}
// Apply procedure
let result = self.apply(proc.clone(), proc_args)?;
result_vec.push(result);
}
// Convert result vector back to list
let mut result_list = Value::Nil;
for elem in result_vec.into_iter().rev() {
result_list = Value::cons(elem, result_list);
}
Ok(result_list)
}
/// (for-each proc list1 list2 ...)
///
/// R4RS: Apply procedure to corresponding elements of lists for side effects.
/// All lists must have the same length.
/// Returns unspecified.
///
/// Example: (for-each display '("a" "b" "c"))
fn eval_for_each(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() < 2 {
return Err(EvalError::new(
"for-each requires at least 2 arguments".to_string(),
));
}
// Evaluate the procedure
let proc = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate all lists
let mut lists = Vec::new();
for i in 1..args_vec.len() {
let list = self.eval_inner(args_vec[i].clone(), env.clone())?;
let list_vec = self.list_to_vec(list)?;
lists.push(list_vec);
}
// Check all lists have the same length
if lists.is_empty() {
return Ok(Value::Unspecified);
}
let length = lists[0].len();
for list in &lists[1..] {
if list.len() != length {
return Err(EvalError::new(
"for-each: all lists must have the same length".to_string(),
));
}
}
// Apply procedure to corresponding elements (for side effects)
for i in 0..length {
// Gather i-th element from each list
let mut proc_args = Vec::new();
for list in &lists {
proc_args.push(list[i].clone());
}
// Apply procedure for side effects
self.apply(proc.clone(), proc_args)?;
}
Ok(Value::Unspecified)
}
/// (node-list-filter predicate node-list)
///
/// (node-list-filter pred node-list) → node-list
///
/// Returns a node-list containing only nodes for which predicate returns #t.
/// DSSSL: Filter a node-list based on a predicate function.
fn eval_node_list_filter(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new("node-list-filter requires exactly 2 arguments".to_string()));
}
// Evaluate the predicate
let pred = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate the node-list
let node_list_val = self.eval_inner(args_vec[1].clone(), env.clone())?;
match node_list_val {
Value::NodeList(ref nl) => {
let mut filtered_nodes = Vec::new();
// Iterate through the node-list
let mut index = 0;
loop {
if let Some(node) = nl.get(index) {
// Apply predicate to this node
let node_val = Value::node(node);
let result = self.apply(pred.clone(), vec![node_val.clone()])?;
// If predicate returns a truthy value (anything except #f), include this node
if !matches!(result, Value::Bool(false)) {
// Need to get the node again since we consumed it
if let Value::Node(n) = node_val {
filtered_nodes.push(n.as_ref().clone_node());
}
}
index += 1;
} else {
break;
}
}
Ok(Value::node_list(Box::new(crate::grove::VecNodeList::new(filtered_nodes))))
}
_ => Err(EvalError::new(format!("node-list-filter: second argument not a node-list: {:?}", node_list_val))),
}
}
/// (node-list-map proc node-list) → node-list
///
/// Applies proc to each node in node-list and returns a flattened node-list.
/// Each result must be a node-list or a single node (which is treated as a singleton node-list).
/// Results are concatenated (flattened) into a single node-list.
/// If proc returns #f or any non-node value, processing stops (OpenJade compatibility).
///
/// DSSSL: Maps a procedure over a node-list, flattening results into a single node-list.
/// OpenJade: MapNodeListObj - stops processing when proc returns a non-node-list value.
fn eval_node_list_map(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new("node-list-map requires exactly 2 arguments".to_string()));
}
// Evaluate the procedure
let proc = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate the node-list
let node_list_val = self.eval_inner(args_vec[1].clone(), env.clone())?;
// Collect all nodes from mapping results (flattened)
let mut result_nodes: Vec<Box<dyn crate::grove::Node>> = Vec::new();
match node_list_val {
Value::Node(ref n) => {
// Single node - apply proc and collect result
let node_val = Value::node(n.as_ref().clone_node());
let result = self.apply(proc, vec![node_val])?;
// OpenJade: Result must be node or node-list. If not, stop processing.
// Single nodes are auto-converted to singleton node-lists (DSSSL spec)
match result {
Value::Node(n) => {
// Single node - treat as singleton node-list
result_nodes.push(n.as_ref().clone_node());
}
Value::NodeList(nl) => {
// Node-list - flatten all nodes
let mut index = 0;
while let Some(node) = nl.get(index) {
result_nodes.push(node);
index += 1;
}
}
_ => {
// Non-node result (e.g., #f) - stop processing (OpenJade compat)
// Return empty node-list
}
}
}
Value::NodeList(ref nl) => {
// Iterate through the node-list
let mut index = 0;
loop {
if let Some(node) = nl.get(index) {
// Apply procedure to this node
let node_val = Value::node(node);
let result = self.apply(proc.clone(), vec![node_val])?;
// OpenJade: Result must be node or node-list. If not, stop processing.
match result {
Value::Node(n) => {
// Single node - treat as singleton node-list
result_nodes.push(n.as_ref().clone_node());
index += 1;
}
Value::NodeList(nl_result) => {
// Node-list - flatten all nodes
let mut nl_index = 0;
while let Some(node) = nl_result.get(nl_index) {
result_nodes.push(node);
nl_index += 1;
}
index += 1;
}
_ => {
// Non-node result (e.g., #f) - stop processing (OpenJade compat)
break;
}
}
} else {
break;
}
}
}
_ => return Err(EvalError::new(format!("node-list-map: second argument must be a node or node-list: {:?}", node_list_val))),
}
// Return flattened node-list
Ok(Value::node_list(Box::new(crate::grove::VecNodeList::new(result_nodes))))
}
/// (node-list-some? predicate node-list) → boolean
///
/// Returns #t if the predicate returns true for at least one node in the node-list.
/// Returns #f if the node-list is empty or the predicate returns false for all nodes.
/// DSSSL: Test if any node in the node-list satisfies the predicate.
fn eval_node_list_some(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 2 {
return Err(EvalError::new("node-list-some? requires exactly 2 arguments".to_string()));
}
// Evaluate the predicate
let pred = self.eval_inner(args_vec[0].clone(), env.clone())?;
// Evaluate the node-list
let node_list_val = self.eval_inner(args_vec[1].clone(), env.clone())?;
match node_list_val {
Value::NodeList(ref nl) => {
// Iterate through the node-list
let mut index = 0;
loop {
if let Some(node) = nl.get(index) {
// Apply predicate to this node
let node_val = Value::node(node);
let result = self.apply(pred.clone(), vec![node_val])?;
// If predicate returns a truthy value (anything except #f), return #t immediately
if !matches!(result, Value::Bool(false)) {
return Ok(Value::bool(true));
}
index += 1;
} else {
break;
}
}
// If we get here, no node satisfied the predicate
Ok(Value::bool(false))
}
_ => Err(EvalError::new(format!("node-list-some?: second argument not a node-list: {:?}", node_list_val))),
}
}
/// (load filename)
///
/// Load and evaluate Scheme code from a file.
/// Returns the result of the last expression in the file.
fn eval_load(&mut self, args: Value, env: Gc<Environment>) -> EvalResult {
let args_vec = self.list_to_vec(args)?;
if args_vec.len() != 1 {
return Err(EvalError::new(
"load requires exactly 1 argument".to_string(),
));
}
// Evaluate the filename argument
let filename_val = self.eval(args_vec[0].clone(), env.clone())?;
let filename = match filename_val {
Value::String(s) => s.to_string(),
_ => return Err(EvalError::new(
format!("load: filename must be a string, got {:?}", filename_val)
)),
};
// Read the file
let contents = std::fs::read_to_string(&filename)
.map_err(|e| EvalError::new(format!("load: cannot read file '{}': {}", filename, e)))?;
// Parse the file contents with filename for error reporting
let mut parser = crate::scheme::parser::Parser::new_with_filename(&contents, filename.clone());
let mut result = Value::Unspecified;
// Save current source file and position, set to the loaded file for error reporting
let prev_source_file = self.current_source_file.clone();
let prev_position = self.current_position.clone();
self.current_source_file = Some(filename.clone());
// Evaluate each expression in sequence
let eval_result = loop {
// Get position before parsing
let pos = parser.current_position();
match parser.parse() {
Ok(expr) => {
// Set position for this expression
self.current_position = Some(pos);
match self.eval(expr, env.clone()) {
Ok(val) => result = val,
Err(e) => break Err(e),
}
}
Err(e) => {
// Check if we've reached end of input (not an error)
let error_msg = e.to_string();
if error_msg.contains("Unexpected end of input")
|| error_msg.contains("Expected")
|| error_msg.contains("EOF") {
break Ok(result);
}
break Err(EvalError::new(
format!("load: parse error in '{}': {}", filename, e)
));
}
}
};
// Restore previous source file and position
self.current_source_file = prev_source_file;
self.current_position = prev_position;
eval_result
}
// =========================================================================
// Function Application
// =========================================================================
/// Apply a function to arguments
fn eval_application(
&mut self,
operator: Value,
args: Value,
env: Gc<Environment>,
) -> EvalResult {
// Save the position of this application expression (the call site)
let application_pos = self.current_position.clone();
let application_file = self.current_source_file.clone();
// Evaluate operator
let proc = self.eval_inner(operator, env.clone())?;
// Evaluate arguments - extract position from the pair containing each argument
let mut evaled_args = Vec::new();
let mut current_args = args;
loop {
match current_args {
Value::Nil => break,
Value::Pair(ref p) => {
let pair_borrow = p.borrow();
// Extract position from this pair (which contains the argument)
// This gives us the position where the argument appears in the source
if let Some(ref pos) = pair_borrow.pos {
// Translate output position to source position using line mappings
if !self.line_mappings.is_empty() {
if let Some(mapping) = self.line_mappings.iter().find(|m| m.output_line == pos.line) {
self.current_source_file = Some(mapping.source_file.clone());
self.current_position = Some(Position {
line: mapping.source_line,
column: pos.column,
});
} else {
self.current_position = Some(pos.clone());
}
} else {
self.current_position = Some(pos.clone());
}
}
let arg = pair_borrow.car.clone();
let cdr = pair_borrow.cdr.clone();
drop(pair_borrow); // Release borrow before evaluating
evaled_args.push(self.eval_inner(arg, env.clone())?);
current_args = cdr;
}
_ => return Err(EvalError::new("Improper argument list".to_string())),
}
}
// Restore the application position before calling apply
// This ensures that when we push a call frame, we capture the CALL SITE, not the last argument's position
self.current_position = application_pos;
self.current_source_file = application_file;
// Apply procedure
self.apply(proc, evaled_args)
}
/// Apply a procedure to evaluated arguments
fn apply(&mut self, proc: Value, args: Vec<Value>) -> EvalResult {
if let Value::Procedure(ref p) = proc {
match &**p {
Procedure::Primitive { name, func } => {
match *name {
"car" | "cdr" | "cons" | "null?" | "equal?" |
"cadr" | "caddr" | "cadddr" | "list" | "length" |
"reverse" | "append" | "list?" | "list-ref" |
"pair?" | "number?" | "integer?" | "real?" | "string?" |
"symbol?" | "char?" | "boolean?" | "zero?" | "positive?" |
"negative?" | "odd?" | "even?" |
"+" | "-" | "*" | "/" | "quotient" | "remainder" | "modulo" |
"=" | "<" | ">" | "<=" | ">=" |
"abs" | "min" | "max" |
"floor" | "ceiling" | "truncate" | "round" |
"sqrt" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" |
"exp" | "log" | "expt" |
"string-length" | "string-ref" | "substring" | "string-append" |
"string=?" | "string<?" | "string>?" | "string<=?" | "string>=?" |
"string-ci=?" | "string-ci<?" | "string-ci>?" | "string-ci<=?" | "string-ci>=?" |
"char=?" | "char<?" | "char>?" | "char<=?" | "char>=?" |
"char-ci=?" | "char-ci<?" | "char-ci>?" | "char-ci<=?" | "char-ci>=?" |
"char-upcase" | "char-downcase" |
"char-alphabetic?" | "char-numeric?" | "char-whitespace?" |
"char->integer" | "integer->char" |
"char-property" | "char-script-case" |
"symbol->string" | "string->symbol" |
"keyword?" | "keyword->string" | "string->keyword" |
"memq" | "memv" | "member" |
"assq" | "assv" | "assoc" |
"not" | "eq?" | "eqv?" |
"caar" | "cdar" | "cddr" |
"caaar" | "caadr" | "cadar" |
"cdaar" | "cdadr" | "cddar" | "cdddr" |
"vector" | "make-vector" | "vector-length" |
"vector-ref" | "vector-set!" |
"vector->list" | "list->vector" | "vector-fill!" |
"vector?" | "procedure?" |
"set-car!" | "set-cdr!" | "list-tail" |
"string-upcase" | "string-downcase" | "case-fold-down" |
"string-index" |
"string->number" | "number->string" |
"string->list" | "list->string" |
"gcd" | "lcm" |
"exact->inexact" | "inexact->exact" |
"make-string" | "string" | "reverse!" |
"string-set!" | "string-copy" | "string-fill!" |
"char-lower-case?" | "char-upper-case?" |
"last" | "last-pair" | "list-copy" |
"append!" | "iota" |
"take" | "drop" | "split-at" |
"filter" | "remove" |
"numerator" | "denominator" | "rationalize" |
"angle" | "magnitude" |
"null-list?" | "improper-list?" | "circular-list?" |
"bitwise-and" | "bitwise-ior" | "bitwise-xor" | "bitwise-not" |
"arithmetic-shift" | "bit-extract" |
"bitwise-bit-set?" | "bitwise-bit-count" |
"format-number" | "format-number-list" |
"empty-sosofo" | "sosofo-append" | "if-first-page" | "if-front-page" |
"current-node" |
"gi" | "data" | "id" |
"children" | "parent" | "attributes" |
"node-list?" | "empty-node-list" | "node-list-empty?" |
"node-list-length" | "node-list-first" |
"attribute-string" |
"node-list-rest" | "node-list-ref" | "node-list-reverse" |
"node?" | "sosofo?" | "quantity?" |
"color?" | "color" | "display-space?" | "inline-space?" |
"quantity->number" | "number->quantity" | "quantity-convert" |
"device-length" | "label-distance" |
"ancestor" | "descendants" | "follow" | "preced" | "ipreced" |
"node-list-last" | "node-list-union" | "node-list-intersection" |
"node-list-difference" | "node-list-remove-duplicates" |
"select-elements" | "first-sibling?" | "last-sibling?" |
"child-number" | "element-with-id" |
"element-number" | "hierarchical-number" | "hierarchical-number-recursive" |
"ancestors" | "document-element" | "have-ancestor?" |
"match-element?" | "node-list-map" |
"node-property" | "absolute-first-sibling?" | "absolute-last-sibling?" |
"node-list->list" | "node-list-contains?" |
"entity-system-id" | "entity-public-id" | "entity-type" |
"notation-system-id" | "notation-public-id" |
"current-language" | "current-mode" | "current-node-address" |
"current-node-page-number-sosofo" | "debug" |
"add" | "divide" | "equal" | "char-eq" | "char-lt" |
"exact?" | "inexact?" | "error" |
"address?" | "address-local?" | "address-visited?" |
"color-space?" | "color-space" | "display-space" | "inline-space" |
"glyph-id?" | "glyph-id" | "glyph-subst-table?" | "glyph-subst-table" | "glyph-subst" |
"time" | "time->string" | "time<=?" | "time<?" | "time>=?" | "time>?" |
"language?" | "language" | "style?" |
"string-equiv?" | "label-length" | "external-procedure" |
"declaration" | "dtd" | "epilog" | "prolog" | "sgml-declaration" | "sgml-parse" |
"entity-address" | "entity-generated-system-id" | "entity-name-normalize" | "general-name-normalize" | "normalize" |
"first-child-gi" | "tree-root" | "declare-default-language" | "read-entity" | "set-visited!" |
"sosofo-contains-node?" | "page-number-sosofo" | "ifollow" | "with-language" |
"all-element-number" | "ancestor-child-number" | "element-number-list" |
"inherited-attribute-string" | "inherited-element-attribute-string" |
"inherited-start-indent" | "inherited-end-indent" | "inherited-line-spacing" |
"inherited-font-family-name" | "inherited-font-size" | "inherited-font-weight" |
"inherited-font-posture" | "inherited-dbhtml-value" | "inherited-pi-value" |
"node-list" | "node-list=?" | "node-list-count" | "node-list-union-map" |
"node-list-symmetrical-difference" |
"node-list-address" | "node-list-error" | "node-list-no-order" |
"origin-to-subnode-rel-forest-addr" |
"named-node" | "named-node-list?" | "named-node-list-names" |
"select-by-class" | "select-children" |
"process-children-trim" | "process-element-with-id" | "process-first-descendant" |
"process-matching-children" | "next-match" => {
self.apply_primitive(name, &args)
}
// Note: I/O operations (display, write, newline, etc.) stay in non-arena path
// because they need actual side effects (stdout/stdin interaction)
_ => {
// Check if this is a known primitive that should be dispatched to apply_primitive
// This handles marker primitives created during symbol lookup
if self.get_primitive_static_name(name).is_some() {
self.apply_primitive(name, &args)
} else {
// Call the function directly for non-arena primitives (I/O, etc.)
// Don't push call frames for primitives - only for user lambdas
// This matches OpenJade's behavior
func(&args).map_err(|e| self.error_with_stack(e))
}
}
}
}
Procedure::Lambda { params, required_count, optional_defaults, body, env, source, name } => {
// Check argument count - must have at least required_count, at most params.len()
if args.len() < *required_count {
return Err(self.error_with_stack(format!(
"Lambda expects at least {} arguments, got {}",
required_count,
args.len()
)));
}
if args.len() > params.len() {
return Err(self.error_with_stack(format!(
"Lambda expects at most {} arguments, got {}",
params.len(),
args.len()
)));
}
// Save current position (call site) before switching to lambda's definition location
let saved_file = self.current_source_file.clone();
let saved_pos = self.current_position.clone();
// Only push call frame for NAMED functions (not anonymous lambdas)
// This matches OpenJade's behavior - it only tracks named function calls
let pushed_frame = if let Some(func_name) = name.clone() {
let call_site = match (&saved_file, &saved_pos) {
(Some(file), Some(pos)) => Some(SourceInfo {
file: file.clone(),
pos: pos.clone(),
}),
_ => None,
};
self.push_call_frame(func_name, call_site);
true
} else {
false
};
// Switch to lambda's definition location for evaluating the body
if let Some(ref src) = source {
self.current_source_file = Some(src.file.clone());
self.current_position = Some(src.pos.clone());
}
// Create new environment extending the closure environment
let lambda_env = Environment::extend(env.clone());
// Bind required and provided arguments
for (param_name, arg_value) in params.iter().zip(args.iter()) {
lambda_env.define(param_name, arg_value.clone());
}
// Bind optional parameters that weren't provided with their defaults
if args.len() < params.len() {
let num_optional_provided = args.len().saturating_sub(*required_count);
let num_optional_defaults_needed = (params.len() - *required_count) - num_optional_provided;
for i in 0..num_optional_defaults_needed {
let param_idx = *required_count + num_optional_provided + i;
let param_name = ¶ms[param_idx];
let default_expr = &optional_defaults[num_optional_provided + i];
if std::env::var("DEBUG_OPTIONAL").is_ok() {
eprintln!("[DEBUG_OPTIONAL] Evaluating default for param '{}': {:?}", param_name, default_expr);
// Try to look up the parameter name in the environment
if let Some(val) = env.lookup(param_name) {
eprintln!("[DEBUG_OPTIONAL] Found '{}' in closure env: {:?}", param_name, val);
} else {
eprintln!("[DEBUG_OPTIONAL] '{}' not found in closure env (expected)", param_name);
}
}
// Evaluate default expression in the closure environment
let default_value = self.eval_inner(default_expr.clone(), env.clone())?;
if std::env::var("DEBUG_OPTIONAL").is_ok() {
eprintln!("[DEBUG_OPTIONAL] Evaluated to: {:?}", default_value);
}
lambda_env.define(param_name, default_value);
}
}
// Evaluate body in the new environment
let result = self.eval_inner((**body).clone(), lambda_env);
// Restore previous position
self.current_source_file = saved_file;
self.current_position = saved_pos;
// Pop call frame if we pushed one
if pushed_frame {
self.pop_call_frame();
}
result
}
}
} else if let Value::Symbol(sym) = &proc {
// Special handling for symbols returned by external-procedure
// These are primitive names that need to be dispatched to arena primitives
let sym_str = sym.as_ref();
// Dispatch directly to the arena primitive by name
self.apply_primitive(sym_str, &args)
} else {
Err(self.error_with_stack(format!(
"Not a procedure: {:?}",
proc
)))
}
}
}
impl Default for Evaluator {
fn default() -> Self {
Self::new()
}
}
// =============================================================================
// Tests
// =============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn make_env() -> Gc<Environment> {
Environment::new_global()
}
#[test]
fn test_eval_self_evaluating() {
let mut eval = Evaluator::new();
let env = make_env();
assert!(eval.eval(Value::integer(42), env.clone()).unwrap().is_integer());
assert!(eval.eval(Value::bool(true), env.clone()).unwrap().is_bool());
assert!(eval.eval(Value::string("hello".to_string()), env).unwrap().is_string());
}
#[test]
fn test_eval_quote() {
let mut eval = Evaluator::new();
let env = make_env();
// (quote (1 2 3))
let expr = Value::cons(
Value::symbol("quote"),
Value::cons(
Value::cons(
Value::integer(1),
Value::cons(Value::integer(2), Value::cons(Value::integer(3), Value::Nil)),
),
Value::Nil,
),
);
let result = eval.eval(expr, env).unwrap();
assert!(result.is_list());
}
#[test]
fn test_eval_if_true() {
let mut eval = Evaluator::new();
let env = make_env();
// (if #t 1 2)
let expr = Value::cons(
Value::symbol("if"),
Value::cons(
Value::bool(true),
Value::cons(Value::integer(1), Value::cons(Value::integer(2), Value::Nil)),
),
);
let result = eval.eval(expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 1);
} else {
panic!("Expected integer 1");
}
}
#[test]
fn test_eval_if_false() {
let mut eval = Evaluator::new();
let env = make_env();
// (if #f 1 2)
let expr = Value::cons(
Value::symbol("if"),
Value::cons(
Value::bool(false),
Value::cons(Value::integer(1), Value::cons(Value::integer(2), Value::Nil)),
),
);
let result = eval.eval(expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 2);
} else {
panic!("Expected integer 2");
}
}
#[test]
fn test_eval_define() {
let mut eval = Evaluator::new();
let env = make_env();
// (define x 42)
let expr = Value::cons(
Value::symbol("define"),
Value::cons(Value::symbol("x"), Value::cons(Value::integer(42), Value::Nil)),
);
eval.eval(expr, env.clone()).unwrap();
// Check that x is defined
assert!(env.is_defined("x"));
if let Value::Integer(n) = env.lookup("x").unwrap() {
assert_eq!(n, 42);
}
}
#[test]
fn test_eval_symbol_lookup() {
let mut eval = Evaluator::new();
let env = make_env();
env.define("x", Value::integer(99));
let result = eval.eval(Value::symbol("x"), env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 99);
} else {
panic!("Expected integer 99");
}
}
#[test]
fn test_eval_and() {
let mut eval = Evaluator::new();
let env = make_env();
// (and #t #t)
let expr = Value::cons(
Value::symbol("and"),
Value::cons(Value::bool(true), Value::cons(Value::bool(true), Value::Nil)),
);
let result = eval.eval(expr, env.clone()).unwrap();
assert!(result.is_true());
// (and #t #f)
let expr = Value::cons(
Value::symbol("and"),
Value::cons(Value::bool(true), Value::cons(Value::bool(false), Value::Nil)),
);
let result = eval.eval(expr, env).unwrap();
assert!(!result.is_true());
}
#[test]
fn test_eval_or() {
let mut eval = Evaluator::new();
let env = make_env();
// (or #f #t)
let expr = Value::cons(
Value::symbol("or"),
Value::cons(Value::bool(false), Value::cons(Value::bool(true), Value::Nil)),
);
let result = eval.eval(expr, env.clone()).unwrap();
assert!(result.is_true());
// (or #f #f)
let expr = Value::cons(
Value::symbol("or"),
Value::cons(Value::bool(false), Value::cons(Value::bool(false), Value::Nil)),
);
let result = eval.eval(expr, env).unwrap();
assert!(!result.is_true());
}
#[test]
fn test_eval_lambda_creation() {
let mut eval = Evaluator::new();
let env = make_env();
// (lambda (x) x)
let expr = Value::cons(
Value::symbol("lambda"),
Value::cons(
Value::cons(Value::symbol("x"), Value::Nil),
Value::cons(Value::symbol("x"), Value::Nil),
),
);
let result = eval.eval(expr, env).unwrap();
assert!(result.is_procedure());
}
#[test]
fn test_eval_lambda_application() {
let mut eval = Evaluator::new();
let env = make_env();
// ((lambda (x) x) 42)
let lambda_expr = Value::cons(
Value::symbol("lambda"),
Value::cons(
Value::cons(Value::symbol("x"), Value::Nil),
Value::cons(Value::symbol("x"), Value::Nil),
),
);
let app_expr = Value::cons(lambda_expr, Value::cons(Value::integer(42), Value::Nil));
let result = eval.eval(app_expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 42);
} else {
panic!("Expected integer 42");
}
}
#[test]
fn test_eval_lambda_multiple_params() {
let mut eval = Evaluator::new();
let env = make_env();
// ((lambda (x y) x) 1 2) - Just return first param
let params = Value::cons(Value::symbol("x"), Value::cons(Value::symbol("y"), Value::Nil));
let body = Value::symbol("x");
let lambda_expr = Value::cons(Value::symbol("lambda"), Value::cons(params, Value::cons(body, Value::Nil)));
let app_expr = Value::cons(
lambda_expr,
Value::cons(Value::integer(1), Value::cons(Value::integer(2), Value::Nil)),
);
let result = eval.eval(app_expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 1);
} else {
panic!("Expected integer 1");
}
}
#[test]
fn test_eval_lambda_wrong_arg_count() {
let mut eval = Evaluator::new();
let env = make_env();
// ((lambda (x) x) 1 2) - wrong argument count
let lambda_expr = Value::cons(
Value::symbol("lambda"),
Value::cons(
Value::cons(Value::symbol("x"), Value::Nil),
Value::cons(Value::symbol("x"), Value::Nil),
),
);
let app_expr = Value::cons(
lambda_expr,
Value::cons(Value::integer(1), Value::cons(Value::integer(2), Value::Nil)),
);
let result = eval.eval(app_expr, env);
assert!(result.is_err());
}
#[test]
fn test_eval_lambda_closure() {
let mut eval = Evaluator::new();
let env = make_env();
// (define x 10)
env.define("x", Value::integer(10));
// ((lambda (y) x) 20)
// Should capture x from outer environment and ignore y
let lambda_expr = Value::cons(
Value::symbol("lambda"),
Value::cons(
Value::cons(Value::symbol("y"), Value::Nil),
Value::cons(Value::symbol("x"), Value::Nil),
),
);
let app_expr = Value::cons(lambda_expr, Value::cons(Value::integer(20), Value::Nil));
let result = eval.eval(app_expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 10); // Should get x from outer environment
} else {
panic!("Expected integer 10 from closure");
}
}
#[test]
fn test_eval_lambda_no_params() {
let mut eval = Evaluator::new();
let env = make_env();
// ((lambda () 42))
let lambda_expr = Value::cons(
Value::symbol("lambda"),
Value::cons(Value::Nil, Value::cons(Value::integer(42), Value::Nil)),
);
let app_expr = Value::cons(lambda_expr, Value::Nil);
let result = eval.eval(app_expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 42);
} else {
panic!("Expected integer 42");
}
}
#[test]
fn test_eval_lambda_multiple_body_expressions() {
let mut eval = Evaluator::new();
let env = make_env();
// ((lambda (x) 1 2 x) 99)
// Should return x (last expression)
let params = Value::cons(Value::symbol("x"), Value::Nil);
let body1 = Value::integer(1);
let body2 = Value::integer(2);
let body3 = Value::symbol("x");
let lambda_expr = Value::cons(
Value::symbol("lambda"),
Value::cons(
params,
Value::cons(body1, Value::cons(body2, Value::cons(body3, Value::Nil))),
),
);
let app_expr = Value::cons(lambda_expr, Value::cons(Value::integer(99), Value::Nil));
let result = eval.eval(app_expr, env).unwrap();
if let Value::Integer(n) = result {
assert_eq!(n, 99);
} else {
panic!("Expected integer 99");
}
}
#[test]
fn test_element_rule_multiple_sosofos_error() {
let mut eval = Evaluator::new();
let env = make_env();
// (element foo expr1 expr2) - should error
let expr = Value::cons(
Value::symbol("element"),
Value::cons(
Value::symbol("foo"),
Value::cons(
Value::symbol("expr1"),
Value::cons(Value::symbol("expr2"), Value::Nil),
),
),
);
let result = eval.eval(expr, env);
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("can only contain one sosofo expression"));
assert!(err_msg.contains("sosofo-append"));
}
#[test]
fn test_element_rule_single_sosofo_ok() {
let mut eval = Evaluator::new();
let env = make_env();
// (element foo expr) - should succeed
let expr = Value::cons(
Value::symbol("element"),
Value::cons(
Value::symbol("foo"),
Value::cons(Value::symbol("expr"), Value::Nil),
),
);
let result = eval.eval(expr, env);
assert!(result.is_ok());
}
#[test]
fn test_default_rule_multiple_sosofos_error() {
let mut eval = Evaluator::new();
let env = make_env();
// (default expr1 expr2) - should error
let expr = Value::cons(
Value::symbol("default"),
Value::cons(
Value::symbol("expr1"),
Value::cons(Value::symbol("expr2"), Value::Nil),
),
);
let result = eval.eval(expr, env);
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("can only contain one sosofo expression"));
assert!(err_msg.contains("sosofo-append"));
}
#[test]
fn test_default_rule_single_sosofo_ok() {
let mut eval = Evaluator::new();
let env = make_env();
// (default expr) - should succeed
let expr = Value::cons(
Value::symbol("default"),
Value::cons(Value::symbol("expr"), Value::Nil),
);
let result = eval.eval(expr, env);
assert!(result.is_ok());
}
#[test]
fn test_vm_simple_arithmetic() {
let mut eval = Evaluator::new();
eval.enable_vm(); // Enable VM execution
let env = make_env();
// Test: (+ 10 32)
let expr = Value::cons(
Value::symbol("+"),
Value::cons(
Value::Integer(10),
Value::cons(Value::Integer(32), Value::Nil),
),
);
let result = eval.eval(expr, env);
assert!(result.is_ok());
let value = result.unwrap();
assert!(matches!(value, Value::Integer(42)));
}
#[test]
fn test_vm_vs_tree_walker() {
// Test that VM and tree-walker produce the same results
let expr = Value::cons(
Value::symbol("+"),
Value::cons(
Value::Integer(10),
Value::cons(Value::Integer(32), Value::Nil),
),
);
// Tree-walker
let mut eval1 = Evaluator::new();
eval1.disable_vm();
let env1 = make_env();
let result1 = eval1.eval(expr.clone(), env1).unwrap();
// VM
let mut eval2 = Evaluator::new();
eval2.enable_vm();
let env2 = make_env();
let result2 = eval2.eval(expr, env2).unwrap();
// Both should produce Integer(42)
assert!(matches!(result1, Value::Integer(42)));
assert!(matches!(result2, Value::Integer(42)));
}
}