lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
//! Main evaluation engine with tail call optimization.
//!
//! This module implements the core evaluator for Lambdust expressions.
//! It uses a trampoline-based approach to ensure proper tail call optimization
//! and constant stack space usage.

#![allow(missing_docs)]

use super::{
    Environment, ThreadSafeEnvironment, Generation, StackFrame, StackTrace, Value, 
    Continuation, Procedure, PrimitiveProcedure, PrimitiveImpl, Frame
};
use crate::module_system::{ModuleSystem, SchemeLibraryLoader, ImportSpec, ModuleId, ModuleNamespace, ImportConfig};
use crate::runtime::GlobalEnvironmentManager;
use super::value::CaseLambdaProcedure;
use crate::ast::{CaseLambdaClause, Expr, Formals, GuardClause, Program};
use crate::diagnostics::{Error, Result, Span, Spanned};
use crate::effects::{Effect, EffectSystem, EffectLifter, MonadicValue};
use crate::ffi::FfiBridge;
use crate::macro_system::MacroExpander;
use crate::utils::{intern_symbol};
use std::sync::Arc;
use std::rc::Rc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

/// Global counter for continuation IDs.
static CONTINUATION_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Generates a unique continuation ID.
fn next_continuation_id() -> u64 {
    CONTINUATION_COUNTER.fetch_add(1, Ordering::SeqCst)
}

/// The result of a single evaluation step.
///
/// Using this enum allows us to implement proper tail call optimization
/// through a trampoline pattern - the evaluator returns instructions
/// about what to do next rather than directly making recursive calls.
#[derive(Debug, Clone)]
pub enum EvalStep {
    /// Evaluation completed with a value
    Return(Value),
    
    /// Continue evaluation with a new expression
    Continue {
        expr: Spanned<Expr>,
        env: Rc<Environment>,
    },
    
    /// Apply a procedure to arguments (tail call)
    TailCall {
        procedure: Value,
        args: Vec<Value>,
        location: Option<Span>,
    },
    
    /// Handle a captured continuation with non-local jump
    CallContinuation {
        continuation: Arc<Continuation>,
        value: Value,
    },
    
    /// Non-local jump - immediately return value, bypassing all computation
    NonLocalJump {
        value: Value,
        target_stack_depth: usize,
    },
    
    
    /// Evaluation error
    Error(Error),
}

/// The main evaluator for Lambdust expressions.
///
/// This evaluator implements proper Scheme semantics including:
/// - Lexical scoping with closures
/// - Proper tail call optimization
/// - Call/cc support for continuations
/// - Hygienic macro expansion
/// - Effect tracking and transformation
/// - FFI support for calling Rust functions
/// - Comprehensive error reporting with stack traces
#[derive(Debug)]
pub struct Evaluator {
    /// Current generation for garbage collection
    generation: Generation,
    /// Stack trace for error reporting
    stack_trace: StackTrace,
    /// Global environment
    global_env: Rc<Environment>,
    /// Macro expander for hygienic macro expansion
    macro_expander: MacroExpander,
    /// Effect system for tracking and transforming effects
    effect_system: EffectSystem,
    /// Effect lifter for automatic lifting
    effect_lifter: EffectLifter,
    /// FFI bridge for calling Rust functions
    ffi_bridge: FfiBridge,
    /// Evaluation context stack for continuation capture
    context_stack: Vec<Frame>,
    /// Module system for handling imports
    module_system: ModuleSystem,
    /// Scheme library loader for SRFI modules
    scheme_loader: SchemeLibraryLoader,
    /// Active call/cc context for proper continuation scoping
    call_cc_context: Option<u64>,
}

impl Evaluator {
    /// Creates a new evaluator with the global environment.
    pub fn new() -> Self {
        let global_env_manager = Arc::new(GlobalEnvironmentManager::new());
        let module_system = ModuleSystem::new().expect("Failed to create module system");
        let scheme_loader = SchemeLibraryLoader::new(global_env_manager.clone())
            .expect("Failed to create scheme library loader");
        
        Self {
            generation: 0,
            stack_trace: StackTrace::new(),
            global_env: crate::eval::environment::global_environment(),
            macro_expander: MacroExpander::with_builtins(),
            effect_system: EffectSystem::new(),
            effect_lifter: EffectLifter::new(),
            ffi_bridge: FfiBridge::with_builtins(),
            context_stack: Vec::new(),
            module_system,
            scheme_loader,
            call_cc_context: None,
        }
    }

    /// Creates a new evaluator with a custom global environment.
    pub fn with_environment(global_env: Rc<Environment>) -> Self {
        let global_env_manager = Arc::new(GlobalEnvironmentManager::new());
        let module_system = ModuleSystem::new().expect("Failed to create module system");
        let scheme_loader = SchemeLibraryLoader::new(global_env_manager.clone())
            .expect("Failed to create scheme library loader");
        
        Self {
            generation: 0,
            stack_trace: StackTrace::new(),
            global_env,
            macro_expander: MacroExpander::with_builtins(),
            effect_system: EffectSystem::new(),
            effect_lifter: EffectLifter::new(),
            ffi_bridge: FfiBridge::with_builtins(),
            context_stack: Vec::new(),
            module_system,
            scheme_loader,
            call_cc_context: None,
        }
    }

    /// Creates a new evaluator with a custom macro expander.
    pub fn with_macro_expander(macro_expander: MacroExpander) -> Self {
        let global_env_manager = Arc::new(GlobalEnvironmentManager::new());
        let module_system = ModuleSystem::new().expect("Failed to create module system");
        let scheme_loader = SchemeLibraryLoader::new(global_env_manager.clone())
            .expect("Failed to create scheme library loader");
        
        Self {
            generation: 0,
            stack_trace: StackTrace::new(),
            global_env: crate::eval::environment::global_environment(),
            macro_expander,
            effect_system: EffectSystem::new(),
            effect_lifter: EffectLifter::new(),
            ffi_bridge: FfiBridge::with_builtins(),
            context_stack: Vec::new(),
            module_system,
            scheme_loader,
            call_cc_context: None,
        }
    }

    /// Evaluates an expression in the given environment.
    ///
    /// This is the main entry point for expression evaluation.
    /// It first expands macros, then uses a trampoline to ensure proper tail call optimization.
    pub fn eval(&mut self, expr: &Spanned<Expr>, env: Rc<Environment>) -> Result<Value> {
        // First, expand macros in the expression
        let expanded_expr = self.macro_expander.expand(expr)?;
        
        // Set up initial evaluation step with expanded expression
        let mut step = EvalStep::Continue {
            expr: expanded_expr,
            env,
        };

        // Trampoline loop - keeps evaluating until we get a final result
        loop {
            step = match step {
                EvalStep::Return(value) => return Ok(value),
                EvalStep::Error(error) => return Err(Box::new(error)),
                EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                EvalStep::TailCall { procedure, args, location } => {
                    self.apply_procedure(procedure, args, location)
                }
                EvalStep::CallContinuation { continuation, value } => {
                    self.call_continuation(continuation, value)
                }
                EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                    // Non-local jump immediately returns the value, bypassing all computation
                    return Ok(value);
                }
            };
        }
    }

    /// Evaluates a program (sequence of expressions).
    pub fn eval_program(&mut self, program: &Program) -> Result<Value> {
        if program.expressions.is_empty() {
            return Ok(Value::Unspecified);
        }

        // First, expand all macros in the program
        let expanded_program = self.macro_expander.expand_program(program)?;
        
        // Separate defines from other expressions for proper R7RS mutual recursion
        let mut defines = Vec::new();
        let mut other_exprs = Vec::new();
        
        for expr in &expanded_program.expressions {
            if let Expr::Define { .. } = expr.inner {
                defines.push(expr);
            } else {
                other_exprs.push(expr);
            }
        }
        
        // First pass: create bindings for all defines
        for define_expr in &defines {
            if let Expr::Define { name, .. } = &define_expr.inner {
                self.global_env.define(name.clone(), Value::Unspecified);
            }
        }
        
        // Second pass: separate lambda and non-lambda defines
        let mut lambda_defines = Vec::new();
        let mut non_lambda_defines = Vec::new();
        
        for define_expr in &defines {
            if let Expr::Define { value, .. } = &define_expr.inner {
                if matches!(value.inner, Expr::Lambda { .. }) {
                    lambda_defines.push(define_expr);
                } else {
                    non_lambda_defines.push(define_expr);
                }
            }
        }
        
        // Evaluate non-lambda defines first
        for define_expr in &non_lambda_defines {
            let mut step = EvalStep::Continue {
                expr: (**define_expr).clone(),
                env: self.global_env.clone(),
            };

            // Trampoline loop for each define
            loop {
                step = match step {
                    EvalStep::Return(_) => break, // Define returns unspecified
                    EvalStep::Error(error) => return Err(Box::new(error)),
                    EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                    EvalStep::TailCall { procedure, args, location } => {
                        self.apply_procedure(procedure, args, location)
                    }
                    EvalStep::CallContinuation { continuation, value } => {
                        self.call_continuation(continuation, value)
                    }
                    EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                        // Non-local jump immediately returns the value
                        return Ok(value);
                    }
                };
            }
        }
        
        // Now evaluate lambda defines - they will see all bound names
        for define_expr in &lambda_defines {
            let mut step = EvalStep::Continue {
                expr: (**define_expr).clone(),
                env: self.global_env.clone(),
            };

            // Trampoline loop for each define
            loop {
                step = match step {
                    EvalStep::Return(_) => break, // Define returns unspecified
                    EvalStep::Error(error) => return Err(Box::new(error)),
                    EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                    EvalStep::TailCall { procedure, args, location } => {
                        self.apply_procedure(procedure, args, location)
                    }
                    EvalStep::CallContinuation { continuation, value } => {
                        self.call_continuation(continuation, value)
                    }
                    EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                        // Non-local jump immediately returns the value
                        return Ok(value);
                    }
                };
            }
        }
        
        // Finally, evaluate other expressions
        let mut result = Value::Unspecified;
        
        for expr in &other_exprs {
            let mut step = EvalStep::Continue {
                expr: (*expr).clone(),
                env: self.global_env.clone(),
            };

            // Trampoline loop for each expression
            loop {
                step = match step {
                    EvalStep::Return(value) => {
                        result = value;
                        break;
                    }
                    EvalStep::Error(error) => return Err(Box::new(error)),
                    EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                    EvalStep::TailCall { procedure, args, location } => {
                        self.apply_procedure(procedure, args, location)
                    }
                    EvalStep::CallContinuation { continuation, value } => {
                        self.call_continuation(continuation, value)
                    }
                    EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                        // Non-local jump immediately returns the value
                        return Ok(value);
                    }
                };
            }
        }

        Ok(result)
    }

    /// Evaluates a self-evaluating literal expression.
    fn eval_self_evaluating_literal(&mut self, lit: &crate::ast::Literal) -> EvalStep {
        EvalStep::Return(Value::Literal(lit.clone()))
    }

    /// Evaluates a self-evaluating keyword expression.
    fn eval_self_evaluating_keyword(&mut self, k: &str) -> EvalStep {
        EvalStep::Return(Value::Keyword(k.to_string()))
    }

    /// Evaluates an identifier (variable lookup).
    fn eval_identifier(&mut self, name: &str, env: &Rc<Environment>, span: Span) -> EvalStep {
        match env.lookup(name) {
            Some(value) => EvalStep::Return(value),
            None => EvalStep::Error(Error::runtime_error(
                format!("Unbound variable: {name}"),
                Some(span),
            )),
        }
    }

    /// Evaluates a type annotation expression.
    fn eval_type_annotation(&mut self, inner_expr: &Spanned<Expr>, env: Rc<Environment>) -> EvalStep {
        // For now, just evaluate the expression and ignore the type
        // TODO: Integrate with type system
        EvalStep::Continue {
            expr: (*inner_expr).clone(),
            env,
        }
    }

    /// Evaluates a pair construction expression.
    fn eval_pair_construction(&mut self, car: &Spanned<Expr>, cdr: &Spanned<Expr>, env: Rc<Environment>) -> EvalStep {
        // Evaluate both car and cdr, then construct pair
        // For simplicity, not using trampoline here since it's not a tail position
        match self.eval(car, env.clone()) {
            Ok(car_val) => match self.eval(cdr, env) {
                Ok(cdr_val) => EvalStep::Return(Value::pair(car_val, cdr_val)),
                Err(e) => EvalStep::Error(*e),
            },
            Err(e) => EvalStep::Error(*e),
        }
    }

    /// Performs a single evaluation step.
    pub fn eval_step(&mut self, expr: &Spanned<Expr>, env: Rc<Environment>) -> EvalStep {
        match &expr.inner {
            // Self-evaluating expressions
            Expr::Literal(lit) => self.eval_self_evaluating_literal(lit),
            Expr::Keyword(k) => self.eval_self_evaluating_keyword(k),

            // Variable lookup
            Expr::Identifier(name) => self.eval_identifier(name, &env, expr.span),

            // Special forms
            Expr::Quote(quoted) => self.eval_quote(quoted),
            Expr::Quasiquote(template) => self.eval_quasiquote(template, env, expr.span),
            Expr::Unquote(unquoted) => self.eval_unquote(unquoted, env, expr.span),
            Expr::UnquoteSplicing(spliced) => self.eval_unquote_splicing(spliced, env, expr.span),
            Expr::Lambda { formals, metadata, body } => {
                self.eval_lambda(formals, metadata, body, env.clone(), expr.span)
            }
            Expr::CaseLambda { clauses, metadata } => {
                self.eval_case_lambda(clauses, metadata, env.clone(), expr.span)
            }
            Expr::If { test, consequent, alternative } => {
                self.eval_if(test, consequent, alternative.as_ref().map(|boxed| boxed.as_ref()), env, expr.span)
            }
            Expr::Define { name, value, metadata } => {
                self.eval_define(name, value, metadata, env, expr.span)
            }
            Expr::Set { name, value } => {
                self.eval_set(name, value, env, expr.span)
            }
            Expr::DefineSyntax { name, transformer } => {
                self.eval_define_syntax(name, transformer, env, expr.span)
            }
            Expr::SyntaxRules { literals, rules } => {
                self.eval_syntax_rules(literals, rules, env, expr.span)
            }
            Expr::CallCC(proc_expr) => {
                self.eval_call_cc(proc_expr, env, expr.span)
            }
            Expr::Primitive { name, args } => {
                self.eval_primitive(name, args, env, expr.span)
            }
            Expr::TypeAnnotation { expr: inner_expr, type_expr: _ } => {
                self.eval_type_annotation(inner_expr, env)
            }
            Expr::Parameterize { bindings, body } => {
                self.eval_parameterize(bindings, body, env, expr.span)
            }
            Expr::Import { import_specs } => {
                self.eval_import(import_specs, env, expr.span)
            }
            
            Expr::DefineLibrary { name, imports, exports, body } => {
                self.eval_define_library(name, imports, exports, body, env, expr.span)
            }

            // Function application
            Expr::Application { operator, operands } => {
                self.eval_application(operator, operands, env, expr.span)
            }

            // Derived forms (implemented as macros in full system)
            Expr::Begin(exprs) => self.eval_begin(exprs, env, expr.span),
            Expr::Let { bindings, body } => self.eval_let(bindings, body, env, expr.span),
            Expr::LetStar { bindings, body } => self.eval_let_star(bindings, body, env, expr.span),
            Expr::LetRec { bindings, body } => self.eval_letrec(bindings, body, env, expr.span),
            Expr::Cond(clauses) => self.eval_cond(clauses, env, expr.span),
            Expr::And(exprs) => self.eval_and(exprs, env, expr.span),
            Expr::Or(exprs) => self.eval_or(exprs, env, expr.span),
            Expr::Guard { variable, clauses, body } => {
                self.eval_guard(variable, clauses, body, env, expr.span)
            }

            // Compound data structures
            Expr::Pair { car, cdr } => {
                self.eval_pair_construction(car, cdr, env)
            }
            
            // Direct list evaluation (for quoted lists)
            Expr::List(elements) => {
                let mut values = Vec::new();
                for element in elements {
                    match self.ast_to_value(&element.inner) {
                        Ok(value) => values.push(value),
                        Err(e) => return EvalStep::Error(*e),
                    }
                }
                EvalStep::Return(Value::list(values))
            }

            // Unimplemented forms
            _ => EvalStep::Error(Error::runtime_error(
                format!("Unimplemented expression type: {:?}", expr.inner),
                Some(expr.span),
            )),
        }
    }

    /// Evaluates a quote expression.
    fn eval_quote(&mut self, quoted: &Spanned<Expr>) -> EvalStep {
        // Convert AST expression to runtime value
        match self.ast_to_value(&quoted.inner) {
            Ok(value) => EvalStep::Return(value),
            Err(e) => EvalStep::Error(*e),
        }
    }

    /// Evaluates a quasiquote template.
    fn eval_quasiquote(&mut self, template: &Spanned<Expr>, env: Rc<Environment>, span: Span) -> EvalStep {
        match self.quasiquote_expand(template, 1, &env) {
            Ok(value) => EvalStep::Return(value),
            Err(e) => EvalStep::Error(Error::runtime_error(
                format!("Quasiquote expansion error: {e}"),
                Some(span),
            )),
        }
    }

    /// Evaluates an unquote expression (error outside of quasiquote).
    fn eval_unquote(&mut self, _unquoted: &Spanned<Expr>, _env: Rc<Environment>, span: Span) -> EvalStep {
        EvalStep::Error(Error::runtime_error(
            "unquote: not in quasiquote",
            Some(span),
        ))
    }

    /// Evaluates an unquote-splicing expression (error outside of quasiquote).
    fn eval_unquote_splicing(&mut self, _spliced: &Spanned<Expr>, _env: Rc<Environment>, span: Span) -> EvalStep {
        EvalStep::Error(Error::runtime_error(
            "unquote-splicing: not in quasiquote",
            Some(span),
        ))
    }

    /// Core quasiquote expansion with nesting level tracking.
    /// 
    /// This implements the R7RS-small specification for quasiquote:
    /// - level 0: evaluate and substitute
    /// - level > 0: preserve structure while decrementing level for nested unquotes
    fn quasiquote_expand(&mut self, template: &Spanned<Expr>, level: i32, env: &Rc<Environment>) -> Result<Value> {
        match &template.inner {
            // Unquote: evaluate if level == 1, otherwise preserve structure
            Expr::Unquote(inner) => {
                if level == 1 {
                    // Evaluate the unquoted expression
                    self.eval(inner, env.clone())
                } else {
                    // Preserve unquote structure with decremented level
                    let inner_value = self.quasiquote_expand(inner, level - 1, env)?;
                    Ok(Value::list(vec![
                        Value::symbol_from_str("unquote"),
                        inner_value,
                    ]))
                }
            }
            
            // Unquote-splicing: evaluate and splice if level == 1
            Expr::UnquoteSplicing(inner) => {
                if level == 1 {
                    // This should only appear in list contexts - handle in list processing
                    Err(Box::new(Error::runtime_error(
                        "unquote-splicing: not in list context",
                        Some(template.span),
                    )))
                } else {
                    // Preserve unquote-splicing structure with decremented level  
                    let inner_value = self.quasiquote_expand(inner, level - 1, env)?;
                    Ok(Value::list(vec![
                        Value::symbol_from_str("unquote-splicing"),
                        inner_value,
                    ]))
                }
            }
            
            // Nested quasiquote: increment level
            Expr::Quasiquote(inner) => {
                let inner_value = self.quasiquote_expand(inner, level + 1, env)?;
                Ok(Value::list(vec![
                    Value::symbol_from_str("quasiquote"),
                    inner_value,
                ]))
            }
            
            // Lists: process each element, handling splicing
            Expr::List(elements) => {
                self.quasiquote_expand_list(elements, level, env)
            }
            
            // Pairs: process both car and cdr
            Expr::Pair { car, cdr } => {
                let car_value = self.quasiquote_expand(car, level, env)?;
                let cdr_value = self.quasiquote_expand(cdr, level, env)?;
                Ok(Value::pair(car_value, cdr_value))
            }
            
            // Applications that might contain unquoting
            Expr::Application { operator, operands } => {
                // Check for unquote/unquote-splicing in operator position
                match &operator.inner {
                    Expr::Identifier(name) if name == "unquote" && level == 1 => {
                        if operands.len() != 1 {
                            return Err(Box::new(Error::runtime_error(
                                "unquote: wrong number of arguments",
                                Some(template.span),
                            )));
                        }
                        self.eval(&operands[0], env.clone())
                    }
                    Expr::Identifier(name) if name == "unquote-splicing" && level == 1 => {
                        Err(Box::new(Error::runtime_error(
                            "unquote-splicing: not in list context",
                            Some(template.span),
                        )))
                    }
                    _ => {
                        // Regular application - expand operator and operands
                        let op_value = self.quasiquote_expand(operator, level, env)?;
                        let mut operand_values = Vec::new();
                        for operand in operands {
                            operand_values.push(self.quasiquote_expand(operand, level, env)?);
                        }
                        let mut result = vec![op_value];
                        result.extend(operand_values);
                        Ok(Value::list(result))
                    }
                }
            }
            
            // Other expressions: convert to value as-is
            _ => {
                self.ast_to_value(&template.inner)
            }
        }
    }
    
    /// Expands a list in quasiquote context, handling unquote-splicing.
    fn quasiquote_expand_list(&mut self, elements: &[Spanned<Expr>], level: i32, env: &Rc<Environment>) -> Result<Value> {
        let mut result = Vec::new();
        
        for element in elements {
            match &element.inner {
                // Handle unquote-splicing at the correct level
                Expr::UnquoteSplicing(inner) if level == 1 => {
                    let spliced_value = self.eval(inner, env.clone())?;
                    // Splice the list elements into the result
                    match spliced_value {
                        Value::Nil => {
                            // Nothing to splice
                        }
                        Value::Pair(car, cdr) => {
                            // Flatten the list into individual elements
                            let mut current = Value::Pair(car, cdr);
                            while let Value::Pair(car, cdr) = current {
                                result.push((*car).clone());
                                current = (*cdr).clone();
                            }
                            // Handle improper list tail
                            if !matches!(current, Value::Nil) {
                                return Err(Box::new(Error::runtime_error(
                                    "unquote-splicing: not a proper list",
                                    Some(element.span),
                                )));
                            }
                        }
                        _ => {
                            return Err(Box::new(Error::runtime_error(
                                "unquote-splicing: not a list",
                                Some(element.span),
                            )));
                        }
                    }
                }
                
                // Handle applications with unquote-splicing
                Expr::Application { operator, operands } 
                    if matches!(&operator.inner, Expr::Identifier(name) if name == "unquote-splicing") 
                    && level == 1 => {
                    if operands.len() != 1 {
                        return Err(Box::new(Error::runtime_error(
                            "unquote-splicing: wrong number of arguments",
                            Some(element.span),
                        )));
                    }
                    let spliced_value = self.eval(&operands[0], env.clone())?;
                    // Same splicing logic as above
                    match spliced_value {
                        Value::Nil => {}
                        Value::Pair(car, cdr) => {
                            let mut current = Value::Pair(car, cdr);
                            while let Value::Pair(car, cdr) = current {
                                result.push((*car).clone());
                                current = (*cdr).clone();
                            }
                            if !matches!(current, Value::Nil) {
                                return Err(Box::new(Error::runtime_error(
                                    "unquote-splicing: not a proper list",
                                    Some(element.span),
                                )));
                            }
                        }
                        _ => {
                            return Err(Box::new(Error::runtime_error(
                                "unquote-splicing: not a list",
                                Some(element.span),
                            )));
                        }
                    }
                }
                
                // Regular element - expand normally
                _ => {
                    result.push(self.quasiquote_expand(element, level, env)?);
                }
            }
        }
        
        Ok(Value::list(result))
    }

    /// Evaluates a lambda expression (creates a closure).
    fn eval_lambda(
        &mut self,
        formals: &Formals,
        metadata: &HashMap<String, Spanned<Expr>>,
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        if body.is_empty() {
            return EvalStep::Error(Error::runtime_error(
                "Lambda body cannot be empty",
                Some(span),
            ));
        }

        // Evaluate metadata
        let mut eval_metadata = HashMap::new();
        for (key, value_expr) in metadata {
            match self.eval(value_expr, env.clone()) {
                Ok(value) => { eval_metadata.insert(key.clone(), value); }
                Err(e) => return EvalStep::Error(*e),
            }
        }

        let procedure = Procedure {
            formals: formals.clone(),
            body: body.to_vec(),
            environment: env.to_thread_safe(),
            name: eval_metadata.get("name").and_then(|v| v.as_string().map(|s| s.to_string())),
            metadata: eval_metadata,
            source: Some(span),
        };

        EvalStep::Return(Value::Procedure(Arc::new(procedure)))
    }

    /// Evaluates a case-lambda expression (creates a case-lambda procedure).
    fn eval_case_lambda(
        &mut self,
        clauses: &[CaseLambdaClause],
        metadata: &HashMap<String, Spanned<Expr>>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        if clauses.is_empty() {
            return EvalStep::Error(Error::runtime_error(
                "Case-lambda must have at least one clause",
                Some(span),
            ));
        }

        // Validate that all clauses have non-empty bodies
        for (i, clause) in clauses.iter().enumerate() {
            if clause.body.is_empty() {
                return EvalStep::Error(Error::runtime_error(
                    format!("Case-lambda clause {} has empty body", i + 1),
                    Some(span),
                ));
            }
        }

        // Evaluate metadata
        let mut eval_metadata = HashMap::new();
        for (key, value_expr) in metadata {
            match self.eval(value_expr, env.clone()) {
                Ok(value) => { eval_metadata.insert(key.clone(), value); }
                Err(e) => return EvalStep::Error(*e),
            }
        }

        let case_lambda = CaseLambdaProcedure {
            clauses: clauses.to_vec(),
            environment: env.to_thread_safe(),
            name: eval_metadata.get("name").and_then(|v| v.as_string().map(|s| s.to_string())),
            metadata: eval_metadata,
            source: Some(span),
        };

        EvalStep::Return(Value::CaseLambda(Arc::new(case_lambda)))
    }

    /// Evaluates an if expression.
    fn eval_if(
        &mut self,
        test: &Spanned<Expr>,
        consequent: &Spanned<Expr>,
        alternative: Option<&Spanned<Expr>>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        // Push stack frame for error reporting
        self.stack_trace.push(StackFrame::special_form("if".to_string(), Some(span)));

        // Evaluate test expression
        match self.eval(test, env.clone()) {
            Ok(test_value) => {
                self.stack_trace.pop(); // Remove if frame
                
                if test_value.is_truthy() {
                    EvalStep::Continue {
                        expr: consequent.clone(),
                        env,
                    }
                } else if let Some(alt) = alternative {
                    EvalStep::Continue {
                        expr: alt.clone(),
                        env,
                    }
                } else {
                    EvalStep::Return(Value::Unspecified)
                }
            }
            Err(e) => {
                self.stack_trace.pop(); // Remove if frame
                EvalStep::Error(*e)
            }
        }
    }

    /// Evaluates a define expression.
    fn eval_define(
        &mut self,
        name: &str,
        value_expr: &Spanned<Expr>,
        _metadata: &HashMap<String, Spanned<Expr>>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("define".to_string(), Some(span)));

        // Handle recursive function definitions like letrec
        if let Expr::Lambda { .. } = &value_expr.inner {
            // First bind name to unspecified for recursive reference
            env.define(name.to_string(), Value::Unspecified);
            
            // Evaluate the lambda expression
            match self.eval(value_expr, env.clone()) {
                Ok(value) => {
                    // Update the binding
                    env.define(name.to_string(), value.clone());
                    
                    // Fix the procedure's environment if it's a procedure
                    if let Value::Procedure(proc_arc) = value {
                        let proc = proc_arc.as_ref();
                        let updated_proc = Procedure {
                            formals: proc.formals.clone(),
                            body: proc.body.clone(),
                            environment: env.to_thread_safe(), // Capture current environment state
                            name: Some(name.to_string()), // Set the procedure name for recursive reference
                            metadata: proc.metadata.clone(),
                            source: proc.source,
                        };
                        env.define(name.to_string(), Value::Procedure(Arc::new(updated_proc)));
                    }
                    
                    self.stack_trace.pop();
                    EvalStep::Return(Value::Unspecified)
                }
                Err(e) => {
                    self.stack_trace.pop();
                    EvalStep::Error(*e)
                }
            }
        } else {
            // For non-lambda expressions, use normal evaluation
            match self.eval(value_expr, env.clone()) {
                Ok(value) => {
                    env.define(name.to_string(), value);
                    self.stack_trace.pop();
                    EvalStep::Return(Value::Unspecified)
                }
                Err(e) => {
                    self.stack_trace.pop();
                    EvalStep::Error(*e)
                }
            }
        }
    }

    /// Evaluates a set! expression.
    fn eval_set(
        &mut self,
        name: &str,
        value_expr: &Spanned<Expr>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("set!".to_string(), Some(span)));

        match self.eval(value_expr, env.clone()) {
            Ok(value) => {
                // Check if set! should be automatically lifted to State monad
                let args = vec![Value::symbol(crate::utils::intern_symbol(name)), value.clone()];
                if let Some(lifted) = self.effect_lifter.lift_operation("set!", &args) {
                    self.stack_trace.pop();
                    return self.handle_monadic_computation(lifted, env, span);
                }
                
                // Normal set! operation
                if env.set(name, value) {
                    // Increment generation for state change
                    self.generation += 1;
                    let _old_context = self.effect_system.enter_context(vec![Effect::State]);
                    self.stack_trace.pop();
                    EvalStep::Return(Value::Unspecified)
                } else {
                    self.stack_trace.pop();
                    EvalStep::Error(Error::runtime_error(
                        format!("Unbound variable in set!: {name}"),
                        Some(span),
                    ))
                }
            }
            Err(e) => {
                self.stack_trace.pop();
                EvalStep::Error(*e)
            }
        }
    }

    /// Evaluates a define-syntax expression.
    fn eval_define_syntax(
        &mut self,
        name: &str,
        transformer: &Spanned<Expr>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("define-syntax".to_string(), Some(span)));

        // Parse the transformer and add it to the macro environment
        match self.parse_syntax_transformer(transformer, env) {
            Ok(macro_transformer) => {
                self.macro_expander.define_macro(name.to_string(), macro_transformer);
                self.stack_trace.pop();
                EvalStep::Return(Value::Unspecified)
            }
            Err(e) => {
                self.stack_trace.pop();
                EvalStep::Error(*e)
            }
        }
    }

    /// Evaluates a syntax-rules expression.
    fn eval_syntax_rules(
        &mut self,
        literals: &[String],
        rules: &[(Spanned<Expr>, Spanned<Expr>)],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("syntax-rules".to_string(), Some(span)));

        // Create a syntax-rules transformer
        let syntax_rules_expr = Spanned::new(
            Expr::SyntaxRules {
                literals: literals.to_vec(),
                rules: rules.to_vec(),
            },
            span,
        );

        match crate::macro_system::parse_syntax_rules(&syntax_rules_expr, env) {
            Ok(syntax_rules_transformer) => {
                let macro_transformer = crate::macro_system::syntax_rules_to_macro_transformer(syntax_rules_transformer);
                // For direct syntax-rules evaluation, we could return a procedure
                // but typically syntax-rules is only used within define-syntax
                self.stack_trace.pop();
                EvalStep::Return(Value::Unspecified) // Or could return a macro transformer value
            }
            Err(e) => {
                self.stack_trace.pop();
                EvalStep::Error(*e)
            }
        }
    }

    /// Evaluates a call/cc expression.
    fn eval_call_cc(
        &mut self,
        proc_expr: &Spanned<Expr>,
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("call/cc".to_string(), Some(span)));

        // Capture the current continuation BEFORE evaluating the procedure
        // This captures the context surrounding the call/cc expression
        let continuation = self.capture_continuation(env.clone(), None);
        let cont_value = Value::Continuation(Arc::new(continuation));

        // Evaluate the procedure
        match self.eval(proc_expr, env.clone()) {
            Ok(procedure) => {
                self.stack_trace.pop();
                
                // Apply the procedure to the continuation
                // This is where the magic happens - the procedure receives the continuation
                // that represents "the rest of the computation after call/cc returns"
                EvalStep::TailCall {
                    procedure,
                    args: vec![cont_value],
                    location: Some(span),
                }
            }
            Err(e) => {
                self.stack_trace.pop();
                EvalStep::Error(*e)
            }
        }
    }

    /// Evaluates a primitive expression.
    fn eval_primitive(
        &mut self,
        name: &str,
        args: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("primitive".to_string(), Some(span)));

        // Evaluate all arguments
        let mut eval_args = Vec::new();
        for arg in args {
            match self.eval(arg, env.clone()) {
                Ok(value) => eval_args.push(value),
                Err(e) => {
                    self.stack_trace.pop();
                    return EvalStep::Error(*e);
                }
            }
        }

        // Call the FFI function through the bridge
        match self.ffi_bridge.call_rust_function(name, &eval_args) {
            Ok(result) => {
                self.stack_trace.pop();
                EvalStep::Return(result)
            }
            Err(e) => {
                // Create a new error with span information
                let error_with_span = match *e {
                    Error::RuntimeError { message, .. } => Box::new(Error::runtime_error(message, Some(span))),
                    _ => e,
                };
                self.stack_trace.pop();
                EvalStep::Error(*error_with_span)
            }
        }
    }

    /// Evaluates a function application.
    fn eval_application(
        &mut self,
        operator: &Spanned<Expr>,
        operands: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        // Check if this is a function call that should be automatically lifted
        if let Expr::Identifier(op_name) = &operator.inner {
            // Evaluate operands first for effect lifting
            let mut args = Vec::new();
            for operand in operands {
                match self.eval(operand, env.clone()) {
                    Ok(value) => args.push(value),
                    Err(e) => return EvalStep::Error(*e),
                }
            }
            
            // Check if this operation should be lifted
            let _current_effects = self.effect_system.context().effects();
            if let Some(lifted) = self.effect_lifter.lift_operation(op_name, &args) {
                // Handle the lifted monadic computation
                return self.handle_monadic_computation(lifted, env, span);
            }
        }
        
        // For proper continuation support, we need to evaluate operator and operands
        // through the trampoline system instead of direct eval() calls
        // This ensures that continuation calls can properly escape from deep evaluation contexts
        
        // Use a more robust evaluation approach that handles continuations properly
        self.eval_application_with_continuation_support(operator, operands, env, span)
    }
    
    /// Evaluates application with proper continuation support.
    /// This method handles continuation calls that can escape from deep evaluation contexts.
    fn eval_application_with_continuation_support(
        &mut self,
        operator: &Spanned<Expr>,
        operands: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        // First, evaluate the operator
        let mut step = EvalStep::Continue {
            expr: operator.clone(),
            env: env.clone(),
        };
        
        // Use mini-trampoline to evaluate operator
        let procedure = loop {
            step = match step {
                EvalStep::Return(value) => break value,
                EvalStep::Error(error) => return EvalStep::Error(error),
                EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                    // Continuation call during operator evaluation 
                    // Return the continuation value directly
                    return EvalStep::Return(value);
                }
                EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                EvalStep::TailCall { procedure, args, location } => {
                    self.apply_procedure(procedure, args, location)
                }
                EvalStep::CallContinuation { continuation, value } => {
                    self.call_continuation(continuation, value)
                }
            };
        };
        
        // Now evaluate operands one by one
        let mut args = Vec::new();
        for operand in operands {
            let mut step = EvalStep::Continue {
                expr: operand.clone(),
                env: env.clone(),
            };
            
            // Use mini-trampoline to evaluate each operand
            let arg_value = loop {
                step = match step {
                    EvalStep::Return(value) => break value,
                    EvalStep::Error(error) => return EvalStep::Error(error),
                    EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                        // Continuation call during operand evaluation 
                        // This means a continuation was called somewhere in the operand
                        // We should return this value instead of continuing with application
                        return EvalStep::Return(value);
                    }
                    EvalStep::Continue { expr, env } => self.eval_step(&expr, env),
                    EvalStep::TailCall { procedure, args, location } => {
                        self.apply_procedure(procedure, args, location)
                    }
                    EvalStep::CallContinuation { continuation, value } => {
                        self.call_continuation(continuation, value)
                    }
                };
            };
            
            args.push(arg_value);
        }
        
        // Apply procedure to arguments (tail call)
        EvalStep::TailCall {
            procedure,
            args,
            location: Some(span),
        }
    }

    /// Applies a procedure to arguments.
    pub fn apply_procedure(&mut self, procedure: Value, args: Vec<Value>, location: Option<Span>) -> EvalStep {
        match procedure {
            Value::Procedure(proc) => self.apply_user_procedure(&proc, args, location),
            Value::CaseLambda(case_lambda) => self.apply_case_lambda_procedure(&case_lambda, args, location),
            Value::Primitive(prim) => self.apply_primitive_procedure(&prim, args, location),
            Value::Continuation(cont) => {
                if args.len() != 1 {
                    EvalStep::Error(Error::runtime_error(
                        format!("Continuation expects 1 argument, got {}", args.len()),
                        location,
                    ))
                } else {
                    EvalStep::CallContinuation {
                        continuation: cont,
                        value: args[0].clone(),
                    }
                }
            }
            Value::Parameter(param) => {
                // Parameters are callable as procedures
                match crate::stdlib::parameters::call_parameter(&param, &args) {
                    Ok(value) => EvalStep::Return(value),
                    Err(e) => EvalStep::Error(*e),
                }
            }
            _ => EvalStep::Error(Error::runtime_error(
                format!("Cannot apply non-procedure: {procedure}"),
                location,
            )),
        }
    }

    /// Applies a user-defined procedure.
    fn apply_user_procedure(
        &mut self,
        proc: &Procedure,
        args: Vec<Value>,
        location: Option<Span>,
    ) -> EvalStep {
        // Check arity
        if let Err(e) = self.check_arity(&proc.formals, args.len(), location) {
            return EvalStep::Error(*e);
        }

        // Create new environment for procedure body
        let mut new_env = proc.environment.extend(self.generation);
        
        // For recursive functions, we need to ensure the function name is correctly bound
        // This is a workaround for the environment snapshot issue in ThreadSafeEnvironment
        if let Some(proc_name) = &proc.name {
            // First check the global environment (for define-based functions)
            if let Some(global_value) = self.global_env.lookup(proc_name) {
                new_env = new_env.define_cow(proc_name.clone(), global_value);
            }
            // TODO: Also check parent environments for letrec-based functions
        }
        
        // Bind parameters using thread-safe environment
        let bound_env = match self.bind_parameters_thread_safe(&proc.formals, &args, new_env, location) {
            Ok(env) => env,
            Err(e) => return EvalStep::Error(*e),
        };

        // Push context frame for continuation capture
        self.push_context_frame(Frame::ProcedureCall {
            procedure_name: proc.name.clone(),
            remaining_body: proc.body.clone(),
            environment: bound_env.clone(),
            source: location.unwrap_or_default(),
        });

        // Push stack frame
        self.stack_trace.push(StackFrame::procedure_call(proc.name.clone(), location));

        // Convert back to legacy environment for eval_sequence
        let legacy_env = bound_env.to_legacy();
        
        // Evaluate body in sequence (implicit begin)
        let result = self.eval_sequence(&proc.body, legacy_env);
        
        // Pop context frame when procedure completes
        self.pop_context_frame();
        
        result
    }

    /// Applies a case-lambda procedure with arity dispatch.
    fn apply_case_lambda_procedure(
        &mut self,
        case_lambda: &CaseLambdaProcedure,
        args: Vec<Value>,
        location: Option<Span>,
    ) -> EvalStep {
        let arg_count = args.len();
        
        // Find the first matching clause
        for clause in case_lambda.clauses.iter() {
            if self.formals_match_arity(&clause.formals, arg_count) {
                // Create temporary procedure from matching clause
                let temp_proc = Procedure {
                    formals: clause.formals.clone(),
                    body: clause.body.clone(),
                    environment: case_lambda.environment.clone(),
                    name: case_lambda.name.clone(),
                    metadata: case_lambda.metadata.clone(),
                    source: case_lambda.source,
                };
                
                // Apply the temporary procedure
                return self.apply_user_procedure(&temp_proc, args, location);
            }
        }
        
        // No matching clause found - generate helpful error
        let clause_info: Vec<String> = case_lambda.clauses
            .iter()
            .enumerate()
            .map(|(i, clause)| {
                format!("clause {}: {}", i + 1, self.formals_arity_description(&clause.formals))
            })
            .collect();
        
        let proc_name = case_lambda.name
            .as_ref()
            .map(|n| format!("case-lambda procedure '{n}'"))
            .unwrap_or_else(|| "case-lambda procedure".to_string());
        
        EvalStep::Error(Error::runtime_error(
            format!(
                "{} called with {} arguments, but no clause matches. Available clauses: {}",
                proc_name,
                arg_count,
                clause_info.join(", ")
            ),
            location,
        ))
    }

    /// Applies a primitive procedure.
    fn apply_primitive_procedure(
        &mut self,
        prim: &PrimitiveProcedure,
        args: Vec<Value>,
        location: Option<Span>,
    ) -> EvalStep {
        // Check arity
        if args.len() < prim.arity_min {
            return EvalStep::Error(Error::runtime_error(
                format!(
                    "{} expects at least {} arguments, got {}",
                    prim.name, prim.arity_min, args.len()
                ),
                location,
            ));
        }

        if let Some(max) = prim.arity_max {
            if args.len() > max {
                return EvalStep::Error(Error::runtime_error(
                    format!(
                        "{} expects at most {} arguments, got {}",
                        prim.name, max, args.len()
                    ),
                    location,
                ));
            }
        }

        // Track effects from the primitive
        if !prim.effects.is_empty() && !prim.effects.contains(&Effect::Pure) {
            let _old_context = self.effect_system.enter_context(prim.effects.clone());
            
            // For state-modifying operations, increment generation
            if prim.effects.contains(&Effect::State) {
                self.generation += 1;
            }
        }

        // Push stack frame
        self.stack_trace.push(StackFrame::primitive(prim.name.clone(), location));

        // Call implementation
        let result = match &prim.implementation {
            PrimitiveImpl::RustFn(f) => f(&args),
            PrimitiveImpl::Native(f) => f(&args),
            PrimitiveImpl::EvaluatorIntegrated(f) => f(self, &args),
            PrimitiveImpl::ForeignFn { library: _, symbol: _ } => {
                // TODO: Implement FFI calls
                Err(Box::new(Error::runtime_error(
                    "FFI not yet implemented".to_string(),
                    location,
                )))
            }
        };

        self.stack_trace.pop();

        match result {
            Ok(value) => EvalStep::Return(value),
            Err(e) => EvalStep::Error(*e),
        }
    }

    /// Calls a continuation.
    pub fn call_continuation(&mut self, continuation: Arc<Continuation>, value: Value) -> EvalStep {
        // Restore the continuation context and continue computation with the provided value
        self.restore_continuation(&continuation, value)
    }

    /// Captures the current continuation.
    /// This preserves the evaluation context so it can be restored during continuation invocation.
    fn capture_continuation(&self, env: Rc<Environment>, current_expr: Option<Spanned<Expr>>) -> Continuation {
        // Clone the current context stack - this represents the "rest of the computation"
        // that would normally be executed after the call/cc returns
        let captured_stack = self.context_stack.clone();
        
        // Create the continuation with captured evaluation context
        Continuation::new(
            captured_stack,
            env.to_thread_safe(),
            next_continuation_id(),
            current_expr,
        )
    }

    /// Restores a captured continuation and returns the given value.
    /// This implements the non-local jump semantics of call/cc.
    fn restore_continuation(&mut self, continuation: &Continuation, value: Value) -> EvalStep {
        // Restore the context stack to the state when continuation was captured
        self.context_stack = continuation.stack.clone();
        
        // The key insight: we need to perform a controlled non-local jump that
        // escapes from the current procedure context but preserves the outer
        // computation context that was captured in the continuation
        EvalStep::NonLocalJump {
            value,
            target_stack_depth: continuation.stack.len(),
        }
    }

    /// Pushes a frame onto the context stack.
    fn push_context_frame(&mut self, frame: Frame) {
        self.context_stack.push(frame);
    }

    /// Pops a frame from the context stack.
    fn pop_context_frame(&mut self) -> Option<Frame> {
        self.context_stack.pop()
    }

    // Helper methods for derived forms

    /// Evaluates a begin expression.
    fn eval_begin(&mut self, exprs: &[Spanned<Expr>], env: Rc<Environment>, span: Span) -> EvalStep {
        if exprs.is_empty() {
            return EvalStep::Error(Error::runtime_error(
                "Begin form cannot be empty",
                Some(span),
            ));
        }

        self.eval_sequence(exprs, env)
    }

    /// Evaluates a sequence of expressions.
    fn eval_sequence(&mut self, exprs: &[Spanned<Expr>], env: Rc<Environment>) -> EvalStep {
        if exprs.is_empty() {
            return EvalStep::Return(Value::Unspecified);
        }

        // Evaluate all but the last expression for side effects
        for expr in &exprs[..exprs.len() - 1] {
            if let Err(e) = self.eval(expr, env.clone()) {
                return EvalStep::Error(*e);
            }
        }

        // Tail call the last expression
        EvalStep::Continue {
            expr: exprs[exprs.len() - 1].clone(),
            env,
        }
    }

    /// Evaluates a let expression.
    /// 
    /// `let` is implemented by transformation to lambda application:
    /// `(let ((x e1) (y e2)) body...)` => `((lambda (x y) body...) e1 e2)`
    fn eval_let(
        &mut self,
        bindings: &[crate::ast::Binding],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        if bindings.is_empty() {
            // Empty let - just evaluate the body in current environment
            return self.eval_sequence(body, env);
        }

        // Extract names and values from bindings
        let names: Vec<String> = bindings.iter().map(|b| b.name.clone()).collect();
        let values: Vec<Spanned<Expr>> = bindings.iter().map(|b| b.value.clone()).collect();

        // Create formals for the lambda
        let formals = Formals::Fixed(names);

        // Create the lambda expression
        let lambda_expr = Expr::Lambda {
            formals,
            metadata: std::collections::HashMap::new(),
            body: body.to_vec(),
        };

        // Create the lambda application
        let app_expr = Expr::Application {
            operator: Box::new(Spanned::new(lambda_expr, span)),
            operands: values,
        };

        // Continue evaluation with the transformed expression
        EvalStep::Continue {
            expr: Spanned::new(app_expr, span),
            env,
        }
    }

    /// Evaluates a let* expression.
    /// 
    /// `let*` is implemented by transformation to nested lambda applications:
    /// `(let* ((x e1) (y e2)) body...)` => `((lambda (x) ((lambda (y) body...) e2)) e1)`
    fn eval_let_star(
        &mut self,
        bindings: &[crate::ast::Binding],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        if bindings.is_empty() {
            // Empty let* - just evaluate the body in current environment
            return self.eval_sequence(body, env);
        }

        // Transform let* to nested lambda applications (right-to-left)
        let mut result_expr = if body.len() == 1 {
            // Single body expression
            body[0].inner.clone()
        } else {
            // Multiple body expressions - wrap in begin
            Expr::Begin(body.to_vec())
        };

        // Build nested lambda applications from right to left
        for binding in bindings.iter().rev() {
            let lambda_expr = Expr::Lambda {
                formals: Formals::Fixed(vec![binding.name.clone()]),
                metadata: std::collections::HashMap::new(),
                body: vec![Spanned::new(result_expr, span)],
            };

            result_expr = Expr::Application {
                operator: Box::new(Spanned::new(lambda_expr, span)),
                operands: vec![binding.value.clone()],
            };
        }

        // Continue evaluation with the transformed expression
        EvalStep::Continue {
            expr: Spanned::new(result_expr, span),
            env,
        }
    }

    /// Evaluates a letrec expression.
    /// 
    /// `letrec` uses the "assignment" transformation approach:
    /// Transform to: (let ((x #<unspecified>) ...) (set! x expr) ... body...)
    /// This allows recursive references to work properly.
    fn eval_letrec(
        &mut self,
        bindings: &[crate::ast::Binding],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        if bindings.is_empty() {
            // Empty letrec - just evaluate the body in current environment
            return self.eval_sequence(body, env);
        }

        // Transform letrec to let + set! pattern
        // (letrec ((x e1) (y e2)) body...) 
        // =>
        // (let ((x #<unspecified>) (y #<unspecified>)) (set! x e1) (set! y e2) body...)
        
        // Create let bindings with unspecified values
        let let_bindings: Vec<crate::ast::Binding> = bindings.iter().map(|b| {
            crate::ast::Binding {
                name: b.name.clone(),
                value: Spanned::new(
                    Expr::Literal(crate::ast::Literal::Unspecified),
                    span
                ),
            }
        }).collect();

        // Create set! expressions
        let mut set_exprs: Vec<Spanned<Expr>> = bindings.iter().map(|b| {
            Spanned::new(
                Expr::Set {
                    name: b.name.clone(),
                    value: Box::new(b.value.clone()),
                },
                span
            )
        }).collect();

        // Add body expressions
        set_exprs.extend_from_slice(body);

        // Create the transformed let expression
        let transformed_expr = Expr::Let {
            bindings: let_bindings,
            body: set_exprs,
        };

        // Continue evaluation with the transformed expression
        EvalStep::Continue {
            expr: Spanned::new(transformed_expr, span),
            env,
        }
    }


    /// Evaluates a cond expression.
    fn eval_cond(
        &mut self,
        clauses: &[crate::ast::CondClause],
        env: Rc<Environment>,
        _span: Span,
    ) -> EvalStep {
        for clause in clauses {
            // Check if this is an else clause
            if let Expr::Identifier(name) = &clause.test.inner {
                if name == "else" {
                    return self.eval_sequence(&clause.body, env);
                }
            }

            // Evaluate test
            match self.eval(&clause.test, env.clone()) {
                Ok(test_value) => {
                    if test_value.is_truthy() {
                        return self.eval_sequence(&clause.body, env);
                    }
                }
                Err(e) => return EvalStep::Error(*e),
            }
        }

        // No clause matched
        EvalStep::Return(Value::Unspecified)
    }

    /// Evaluates an and expression.
    fn eval_and(&mut self, exprs: &[Spanned<Expr>], env: Rc<Environment>, _span: Span) -> EvalStep {
        if exprs.is_empty() {
            return EvalStep::Return(Value::t());
        }

        // Evaluate expressions left to right, short-circuiting on false
        for expr in &exprs[..exprs.len() - 1] {
            match self.eval(expr, env.clone()) {
                Ok(value) => {
                    if value.is_falsy() {
                        return EvalStep::Return(value);
                    }
                }
                Err(e) => return EvalStep::Error(*e),
            }
        }

        // Tail call the last expression
        EvalStep::Continue {
            expr: exprs[exprs.len() - 1].clone(),
            env,
        }
    }

    /// Evaluates an or expression.
    fn eval_or(&mut self, exprs: &[Spanned<Expr>], env: Rc<Environment>, _span: Span) -> EvalStep {
        if exprs.is_empty() {
            return EvalStep::Return(Value::f());
        }

        // Evaluate expressions left to right, short-circuiting on true
        for expr in &exprs[..exprs.len() - 1] {
            match self.eval(expr, env.clone()) {
                Ok(value) => {
                    if value.is_truthy() {
                        return EvalStep::Return(value);
                    }
                }
                Err(e) => return EvalStep::Error(*e),
            }
        }

        // Tail call the last expression
        EvalStep::Continue {
            expr: exprs[exprs.len() - 1].clone(),
            env,
        }
    }

    /// Evaluates a guard expression for exception handling.
    fn eval_guard(
        &mut self,
        variable: &str,
        clauses: &[GuardClause],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("guard".to_string(), Some(span)));
        
        // Try to evaluate the body
        let result = self.eval_sequence(body, env.clone());
        
        match result {
            EvalStep::Return(value) => {
                // Body completed normally - return the value
                self.stack_trace.pop();
                EvalStep::Return(value)
            }
            EvalStep::Error(Error::Exception { exception, .. }) => {
                // An exception was raised - try to handle it with the clauses
                self.stack_trace.pop();
                
                // Create new environment with exception bound to variable
                let handler_env = env.extend(self.generation);
                handler_env.define(variable.to_string(), Value::exception_object(exception.clone()));
                
                // Try each clause in order
                for clause in clauses {
                    // Evaluate the test condition
                    match self.eval(&clause.test, handler_env.clone()) {
                        Ok(test_result) => {
                            if test_result.is_truthy() {
                                // This clause matches
                                if let Some(ref arrow_expr) = clause.arrow {
                                    // => clause: apply the procedure to the test result
                                    match self.eval(arrow_expr, handler_env.clone()) {
                                        Ok(proc) => {
                                            return EvalStep::TailCall {
                                                procedure: proc,
                                                args: vec![test_result],
                                                location: Some(span),
                                            };
                                        }
                                        Err(e) => return EvalStep::Error(*e),
                                    }
                                } else {
                                    // Regular clause: evaluate the body
                                    return self.eval_sequence(&clause.body, handler_env);
                                }
                            }
                        }
                        Err(e) => {
                            // Error in test expression - this becomes the new exception
                            return EvalStep::Error(*e);
                        }
                    }
                }
                
                // No clause matched - re-raise the exception
                EvalStep::Error(Error::Exception { exception, span: Some(span) })
            }
            other => {
                // Other evaluation outcomes (continue, tail call, etc.) - pass through
                self.stack_trace.pop();
                other
            }
        }
    }

    /// Evaluates a parameterize expression.
    fn eval_parameterize(
        &mut self,
        bindings: &[crate::ast::ParameterBinding],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        use crate::eval::parameter::ParameterBinding;
        use crate::stdlib::parameters::process_parameter_bindings;
        
        self.stack_trace.push(StackFrame::special_form("parameterize".to_string(), Some(span)));
        
        // Convert AST bindings to runtime bindings
        let runtime_bindings = match process_parameter_bindings(bindings, |expr| {
            // We need to evaluate expressions synchronously here
            // Create a temporary evaluator to evaluate the expressions
            match self.eval(&Spanned::new(expr.clone(), span), env.clone()) {
                Ok(value) => Ok(value),
                Err(e) => Err(e),
            }
        }) {
            Ok(bindings) => bindings,
            Err(e) => {
                self.stack_trace.pop();
                return EvalStep::Error(*e);
            }
        };
        
        // Execute the body with the parameter bindings
        let result = ParameterBinding::with_bindings(runtime_bindings, || {
            self.eval_sequence(body, env)
        });
        
        self.stack_trace.pop();
        result
    }

    // Helper methods

    /// Checks if the number of arguments matches the formal parameters.
    fn check_arity(&self, formals: &Formals, arg_count: usize, location: Option<Span>) -> Result<()> {
        match formals {
            Formals::Fixed(params) => {
                if arg_count != params.len() {
                    Err(Box::new(Error::runtime_error(
                        format!("Expected {} arguments, got {}", params.len(), arg_count),
                        location,
                    )))
                } else {
                    Ok(())
                }
            }
            Formals::Variable(_) => Ok(()), // Variable arity accepts any number
            Formals::Mixed { fixed, .. } => {
                if arg_count < fixed.len() {
                    Err(Box::new(Error::runtime_error(
                        format!("Expected at least {} arguments, got {}", fixed.len(), arg_count),
                        location,
                    )))
                } else {
                    Ok(())
                }
            }
            Formals::Keyword { fixed,  .. } => {
                // TODO: Implement proper keyword argument checking
                if arg_count < fixed.len() {
                    Err(Box::new(Error::runtime_error(
                        format!("Expected at least {} arguments, got {}", fixed.len(), arg_count),
                        location,
                    )))
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Checks if formals can accept the given number of arguments (for case-lambda dispatch).
    fn formals_match_arity(&self, formals: &Formals, arg_count: usize) -> bool {
        match formals {
            Formals::Fixed(params) => arg_count == params.len(),
            Formals::Variable(_) => true, // Variable arity accepts any number
            Formals::Mixed { fixed, .. } => arg_count >= fixed.len(),
            Formals::Keyword { fixed, .. } => {
                // TODO: Implement proper keyword argument checking
                arg_count >= fixed.len()
            }
        }
    }

    /// Provides a human-readable description of the arity for a formals pattern.
    fn formals_arity_description(&self, formals: &Formals) -> String {
        match formals {
            Formals::Fixed(params) => {
                if params.len() == 1 {
                    "exactly 1 argument".to_string()
                } else {
                    format!("exactly {} arguments", params.len())
                }
            }
            Formals::Variable(_) => "any number of arguments".to_string(),
            Formals::Mixed { fixed, .. } => {
                if fixed.len() == 1 {
                    "at least 1 argument".to_string()
                } else {
                    format!("at least {} arguments", fixed.len())
                }
            }
            Formals::Keyword { fixed, .. } => {
                // TODO: Implement proper keyword argument description
                if fixed.len() == 1 {
                    "at least 1 argument (with keywords)".to_string()
                } else {
                    format!("at least {} arguments (with keywords)", fixed.len())
                }
            }
        }
    }

    /// Binds formal parameters to actual arguments in the given environment.
    #[allow(dead_code)]
    fn bind_parameters(
        &self,
        formals: &Formals,
        args: &[Value],
        env: &Environment,
        _location: Option<Span>,
    ) -> Result<()> {
        match formals {
            Formals::Fixed(params) => {
                for (param, arg) in params.iter().zip(args.iter()) {
                    env.define(param.clone(), arg.clone());
                }
            }
            Formals::Variable(param) => {
                // Bind all arguments as a list
                let args_list = Value::list(args.to_vec());
                env.define(param.clone(), args_list);
            }
            Formals::Mixed { fixed, rest } => {
                // Bind fixed parameters
                for (param, arg) in fixed.iter().zip(args.iter()) {
                    env.define(param.clone(), arg.clone());
                }
                
                // Bind remaining arguments as a list
                let rest_args = if args.len() > fixed.len() {
                    Value::list(args[fixed.len()..].to_vec())
                } else {
                    Value::Nil
                };
                env.define(rest.clone(), rest_args);
            }
            Formals::Keyword { fixed, rest: _, keywords: _ } => {
                // TODO: Implement proper keyword argument binding
                // For now, just bind fixed parameters
                for (param, arg) in fixed.iter().zip(args.iter()) {
                    env.define(param.clone(), arg.clone());
                }
            }
        }
        
        Ok(())
    }
    
    /// Binds formal parameters using ThreadSafeEnvironment (COW semantics).
    fn bind_parameters_thread_safe(
        &self,
        formals: &Formals,
        args: &[Value],
        env: Arc<ThreadSafeEnvironment>,
        _location: Option<Span>,
    ) -> Result<Arc<ThreadSafeEnvironment>> {
        let mut current_env = env;
        
        match formals {
            Formals::Fixed(params) => {
                for (param, arg) in params.iter().zip(args.iter()) {
                    current_env = current_env.define_cow(param.clone(), arg.clone());
                }
            }
            Formals::Variable(param) => {
                // Bind all arguments as a list
                let args_list = Value::list(args.to_vec());
                current_env = current_env.define_cow(param.clone(), args_list);
            }
            Formals::Mixed { fixed, rest } => {
                // Bind fixed parameters
                for (param, arg) in fixed.iter().zip(args.iter()) {
                    current_env = current_env.define_cow(param.clone(), arg.clone());
                }
                
                // Bind remaining arguments as a list
                let rest_args = if args.len() > fixed.len() {
                    Value::list(args[fixed.len()..].to_vec())
                } else {
                    Value::Nil
                };
                current_env = current_env.define_cow(rest.clone(), rest_args);
            }
            Formals::Keyword { fixed, rest: _, keywords: _ } => {
                // TODO: Implement proper keyword argument binding
                // For now, just bind fixed parameters
                for (param, arg) in fixed.iter().zip(args.iter()) {
                    current_env = current_env.define_cow(param.clone(), arg.clone());
                }
            }
        }
        
        Ok(current_env)
    }

    /// Converts an AST expression to a runtime value (for quote).
    #[allow(clippy::only_used_in_recursion)]
    fn ast_to_value(&self, expr: &Expr) -> Result<Value> {
        match expr {
            Expr::Literal(lit) => Ok(Value::Literal(lit.clone())),
            Expr::Identifier(name) => Ok(Value::Symbol(intern_symbol(name))),
            Expr::Keyword(k) => Ok(Value::Keyword(k.clone())),
            Expr::Pair { car, cdr } => {
                let car_val = self.ast_to_value(&car.inner)?;
                let cdr_val = self.ast_to_value(&cdr.inner)?;
                Ok(Value::pair(car_val, cdr_val))
            }
            Expr::List(elements) => {
                // Convert list elements to values
                let mut values = Vec::new();
                for element in elements {
                    values.push(self.ast_to_value(&element.inner)?);
                }
                Ok(Value::list(values))
            }
            Expr::Application { operator, operands } => {
                // Convert to list
                let mut values = vec![self.ast_to_value(&operator.inner)?];
                for operand in operands {
                    values.push(self.ast_to_value(&operand.inner)?);
                }
                Ok(Value::list(values))
            }
            _ => Ok(Value::list(vec![])), // For now, other forms become empty lists
        }
    }

    /// Parses a syntax transformer expression.
    fn parse_syntax_transformer(
        &self,
        transformer_expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<crate::macro_system::MacroTransformer> {
        match &transformer_expr.inner {
            Expr::SyntaxRules { literals, rules } => {
                // Parse syntax-rules into a transformer
                let syntax_rules_transformer = crate::macro_system::parse_syntax_rules(transformer_expr, env)?;
                Ok(crate::macro_system::syntax_rules_to_macro_transformer(syntax_rules_transformer))
            }
            _ => {
                // For other transformer types (lambda-based macros, etc.)
                // This is a simplified implementation - full support would require
                // evaluating the transformer expression in a macro-time environment
                Err(Box::new(Error::runtime_error(
                    "Only syntax-rules transformers are currently supported".to_string(),
                    Some(transformer_expr.span),
                )))
            }
        }
    }

    /// Gets the current stack trace.
    pub fn stack_trace(&self) -> &StackTrace {
        &self.stack_trace
    }

    /// Increments the generation counter.
    pub fn next_generation(&mut self) {
        self.generation += 1;
    }

    /// Gets a reference to the macro expander.
    pub fn macro_expander(&self) -> &MacroExpander {
        &self.macro_expander
    }

    /// Gets a mutable reference to the macro expander.
    pub fn macro_expander_mut(&mut self) -> &mut MacroExpander {
        &mut self.macro_expander
    }
    
    /// Gets a reference to the effect system.
    pub fn effect_system(&self) -> &EffectSystem {
        &self.effect_system
    }
    
    /// Gets a mutable reference to the effect system.
    pub fn effect_system_mut(&mut self) -> &mut EffectSystem {
        &mut self.effect_system
    }
    
    /// Gets a reference to the effect lifter.
    pub fn effect_lifter(&self) -> &EffectLifter {
        &self.effect_lifter
    }
    
    /// Gets a mutable reference to the effect lifter.
    pub fn effect_lifter_mut(&mut self) -> &mut EffectLifter {
        &mut self.effect_lifter
    }
    
    /// Gets a reference to the FFI bridge.
    pub fn ffi_bridge(&self) -> &FfiBridge {
        &self.ffi_bridge
    }
    
    /// Gets a mutable reference to the FFI bridge.
    pub fn ffi_bridge_mut(&mut self) -> &mut FfiBridge {
        &mut self.ffi_bridge
    }

    /// Evaluates an import expression.
    fn eval_import(
        &mut self,
        import_specs: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("import".to_string(), Some(span)));

        // Set up search paths for SRFI libraries if not already done
        self.setup_library_search_paths();

        // Process each import specification
        for spec_expr in import_specs {
            match self.process_import_spec(spec_expr, env.clone()) {
                Ok(bindings) => {
                    // Import the bindings into the current environment
                    for (name, value) in bindings {
                        env.define(name, value);
                    }
                }
                Err(e) => {
                    self.stack_trace.pop();
                    return EvalStep::Error(*e);
                }
            }
        }

        self.stack_trace.pop();
        EvalStep::Return(Value::Unspecified)
    }

    /// Sets up search paths for library loading.
    fn setup_library_search_paths(&mut self) {
        // Add stdlib path for SRFI modules
        self.scheme_loader.add_search_path("stdlib");
        
        // Initialize from library resolver if available
        self.scheme_loader.initialize_from_library_resolver();
    }

    /// Processes a single import specification.
    fn process_import_spec(&mut self, spec_expr: &Spanned<Expr>, _env: Rc<Environment>) -> Result<HashMap<String, Value>> {
        use crate::module_system::{import::parse_import_spec, ModuleId, ModuleNamespace};
        
        // Convert the spec expression to import specification
        let import_spec = self.parse_import_expression(spec_expr)?;

        // Load the module using the scheme library loader
        match self.scheme_loader.load_library(&import_spec.module_id) {
            Ok(compiled_library) => {
                // Apply import configuration to get final bindings
                crate::module_system::import::apply_import_config(
                    &compiled_library.module.exports,
                    &import_spec.config,
                )
            }
            Err(e) => Err(e),
        }
    }

    /// Parses an import expression into an ImportSpec.
    fn parse_import_expression(&self, spec_expr: &Spanned<Expr>) -> Result<ImportSpec> {
        use crate::module_system::{ImportSpec, ImportConfig, ModuleId, ModuleNamespace};
        
        match &spec_expr.inner {
            Expr::List(elements) => {
                if elements.is_empty() {
                    return Err(Box::new(Error::syntax_error(
                        "Empty import specification".to_string(),
                        Some(spec_expr.span),
                    )));
                }

                // Parse module identifier from first element
                let module_id = self.parse_module_identifier(&elements[0])?;
                
                // For now, we'll support simple imports without configuration
                // TODO: Add support for (only ...), (except ...), (rename ...), (prefix ...)
                let config = ImportConfig::All;

                Ok(ImportSpec { module_id, config })
            }
            // Also handle Application syntax: (srfi 41) gets parsed as (srfi . (41))
            Expr::Application { operator, operands } => {
                // Construct a pseudo-list from the application
                let mut elements = vec![operator.as_ref().clone()];
                elements.extend(operands.iter().cloned());
                
                if elements.is_empty() {
                    return Err(Box::new(Error::syntax_error(
                        "Empty import specification".to_string(),
                        Some(spec_expr.span),
                    )));
                }

                // For applications, the elements directly represent the module components
                let module_id = self.parse_module_identifier_from_elements(&elements)?;
                let config = ImportConfig::All;

                Ok(ImportSpec { module_id, config })
            }
            _ => Err(Box::new(Error::syntax_error(
                format!("Import specification must be a list, found: {:?}", spec_expr.inner),
                Some(spec_expr.span),
            ))),
        }
    }

    /// Parses a module identifier from an expression.
    fn parse_module_identifier(&self, expr: &Spanned<Expr>) -> Result<ModuleId> {
        use crate::module_system::{ModuleId, ModuleNamespace};
        
        match &expr.inner {
            Expr::List(elements) => {
                if elements.is_empty() {
                    return Err(Box::new(Error::syntax_error(
                        "Module identifier cannot be empty".to_string(),
                        Some(expr.span),
                    )));
                }

                let mut components = Vec::new();
                for element in elements {
                    match &element.inner {
                        Expr::Identifier(name) => components.push(name.clone()),
                        Expr::Symbol(name) => components.push(name.clone()),
                        _ => return Err(Box::new(Error::syntax_error(
                            "Module identifier components must be symbols".to_string(),
                            Some(element.span),
                        ))),
                    }
                }

                // Determine namespace based on first component
                let namespace = match components[0].as_str() {
                    "srfi" => ModuleNamespace::SRFI,
                    "scheme" => ModuleNamespace::R7RS,
                    "lambdust" => ModuleNamespace::Builtin,
                    _ => ModuleNamespace::User,
                };

                Ok(ModuleId { components, namespace })
            }
            _ => Err(Box::new(Error::syntax_error(
                "Module identifier must be a list".to_string(),
                Some(expr.span),
            ))),
        }
    }

    /// Parses a module identifier from a vector of expressions.
    fn parse_module_identifier_from_elements(&self, elements: &[Spanned<Expr>]) -> Result<ModuleId> {
        use crate::module_system::{ModuleId, ModuleNamespace};
        
        if elements.is_empty() {
            return Err(Box::new(Error::runtime_error(
                "Module identifier cannot be empty".to_string(),
                None,
            )));
        }

        let mut components = Vec::new();
        for element in elements {
            match &element.inner {
                Expr::Identifier(name) => components.push(name.clone()),
                Expr::Symbol(name) => components.push(name.clone()),
                Expr::Literal(literal) if literal.is_number() => {
                    // Handle numeric components like "41" in (srfi 41)
                    if let Some(n) = literal.to_f64() {
                        components.push(format!("{}", n as i64));
                    } else {
                        components.push("0".to_string());
                    }
                }
                _ => return Err(Box::new(Error::syntax_error(
                    format!("Module identifier components must be symbols or numbers, found: {:?}", element.inner),
                    Some(element.span),
                ))),
            }
        }

        // Debug output to see what we're constructing
        eprintln!("Debug: Constructed module components: {components:?}");

        // Determine namespace based on first component
        let namespace = match components[0].as_str() {
            "srfi" => ModuleNamespace::SRFI,
            "scheme" => ModuleNamespace::R7RS,
            "lambdust" => ModuleNamespace::Builtin,
            _ => ModuleNamespace::User,
        };

        // Strip namespace prefix from components
        let module_components = match namespace {
            ModuleNamespace::SRFI | ModuleNamespace::R7RS | ModuleNamespace::Builtin => {
                if components.len() > 1 {
                    components[1..].to_vec()
                } else {
                    components
                }
            }
            _ => components,
        };

        let module_id = ModuleId { components: module_components, namespace };
        eprintln!("Debug: Final module ID: {module_id:?}");
        
        Ok(module_id)
    }

    /// Handles a monadic computation by executing it and returning the result.
    fn handle_monadic_computation(
        &mut self,
        computation: MonadicValue,
        _env: Rc<Environment>,
        _span: Span,
    ) -> EvalStep {
        match computation {
            MonadicValue::Pure(value) => EvalStep::Return(value),
            MonadicValue::IO(io_comp) => {
                // Execute the IO computation
                match io_comp.execute() {
                    Ok(value) => {
                        // Update effect context to include IO
                        let _old_context = self.effect_system.enter_context(vec![Effect::IO]);
                        EvalStep::Return(value)
                    },
                    Err(e) => EvalStep::Error(*e),
                }
            },
            MonadicValue::State(state_comp) => {
                // Execute the state computation
                match state_comp.execute() {
                    Ok((value, _new_env)) => {
                        // Create a new generation for the state change
                        self.generation += 1;
                        let _old_context = self.effect_system.enter_context(vec![Effect::State]);
                        EvalStep::Return(value)
                    },
                    Err(e) => EvalStep::Error(*e),
                }
            },
            MonadicValue::Error(error_comp) => {
                // Execute the error computation
                match error_comp.execute() {
                    Ok(value) => {
                        let _old_context = self.effect_system.enter_context(vec![Effect::Error]);
                        EvalStep::Return(value)
                    },
                    Err(e) => EvalStep::Error(*e),
                }
            },
            MonadicValue::Combined(combined) => {
                // Handle combined effects by using the primary computation
                self.handle_monadic_computation(combined.primary().clone(), _env, _span)
            }
        }
    }


    /// Evaluates a define-library expression.
    fn eval_define_library(
        &mut self,
        name: &[String],
        imports: &[Spanned<Expr>],
        exports: &[Spanned<Expr>],
        body: &[Spanned<Expr>],
        env: Rc<Environment>,
        span: Span,
    ) -> EvalStep {
        self.stack_trace.push(StackFrame::special_form("define-library".to_string(), Some(span)));

        // For now, this is a simplified implementation that:
        // 1. Processes imports (if any)
        // 2. Evaluates the body expressions
        // 3. Sets up exports (placeholder - full module system integration needed)
        
        // Process imports first
        for import_expr in imports {
            match self.process_import_spec(import_expr, env.clone()) {
                Ok(bindings) => {
                    // Import the bindings into the current environment
                    for (binding_name, value) in bindings {
                        env.define(binding_name, value);
                    }
                }
                Err(e) => {
                    self.stack_trace.pop();
                    return EvalStep::Error(*e);
                }
            }
        }

        // Create a new environment for the library body
        let lib_env = env.extend(self.generation);
        
        // Evaluate body expressions
        let mut last_result = Value::Unspecified;
        for body_expr in body {
            match self.eval(body_expr, lib_env.clone()) {
                Ok(value) => {
                    last_result = value;
                }
                Err(e) => {
                    self.stack_trace.pop();
                    return EvalStep::Error(*e);
                }
            }
        }

        // TODO: Process exports and register the library in the module system
        // For now, we'll skip export processing since it requires full module system integration
        
        eprintln!("Debug: define-library '{}' processed successfully", name.join(" "));
        if !exports.is_empty() {
            eprintln!("Debug: {} exports declared but not yet processed", exports.len());
        }

        self.stack_trace.pop();
        EvalStep::Return(Value::Unspecified)
    }
}

impl Default for Evaluator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{Literal, Expr, Formals};
    use crate::diagnostics::Spanned;

    /// Helper function to create a spanned expression.
    fn spanned(expr: Expr) -> Spanned<Expr> {
        Spanned::new(expr, Span::default())
    }

    /// Helper function to create a simple lambda expression.
    fn make_lambda(param: &str, body: Expr) -> Expr {
        Expr::Lambda {
            formals: Formals::Fixed(vec![param.to_string()]),
            metadata: HashMap::new(),
            body: vec![spanned(body)],
        }
    }

    #[test]
    fn test_continuation_creation() {
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        let continuation = Continuation::new(
            vec![],
            env,
            1,
            None,
        );
        
        assert_eq!(continuation.id, 1);
        assert!(!continuation.is_invoked());
        assert_eq!(continuation.stack.len(), 0);
    }

    #[test]
    fn test_continuation_invocation_tracking() {
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        let continuation = Continuation::new(
            vec![],
            env,
            1,
            None,
        );

        // Initially not invoked
        assert!(!continuation.is_invoked());

        // Mark as invoked
        let was_invoked = continuation.mark_invoked();
        assert!(!was_invoked); // Returns previous state
        assert!(continuation.is_invoked());

        // Try to mark again
        let was_invoked_again = continuation.mark_invoked();
        assert!(was_invoked_again); // Returns previous state (true)
        assert!(continuation.is_invoked());
    }

    #[test]
    fn test_context_stack_management() {
        let mut evaluator = Evaluator::new();
        
        // Initially empty
        assert_eq!(evaluator.context_stack.len(), 0);
        
        // Push a frame
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        let frame = Frame::CallCC {
            environment: env,
            source: Span::default(),
        };
        
        evaluator.push_context_frame(frame);
        assert_eq!(evaluator.context_stack.len(), 1);
        
        // Pop the frame
        let popped = evaluator.pop_context_frame();
        assert!(popped.is_some());
        assert_eq!(evaluator.context_stack.len(), 0);
        
        // Pop from empty stack
        let popped_empty = evaluator.pop_context_frame();
        assert!(popped_empty.is_none());
    }

    #[test]
    fn test_continuation_capture() {
        let mut evaluator = Evaluator::new();
        let env = Rc::new(Environment::new(None, 0));
        
        // Push some context frames first
        let thread_safe_env = env.to_thread_safe();
        evaluator.push_context_frame(Frame::CallCC {
            environment: thread_safe_env.clone(),
            source: Span::default(),
        });
        
        // Capture continuation
        let continuation = evaluator.capture_continuation(env, None);
        
        // Verify captured state
        assert_eq!(continuation.stack.len(), 1);
        assert!(matches!(continuation.stack[0], Frame::CallCC { .. }));
    }

    #[test]
    fn test_simple_call_cc_expression() {
        let mut evaluator = Evaluator::new();
        let env = Rc::new(Environment::new(None, 0));
        
        // Create a simple call/cc expression: (call/cc (lambda (k) 42))
        let lambda_expr = make_lambda("k", Expr::Literal(Literal::integer(42)));
        let call_cc_expr = Expr::CallCC(Box::new(spanned(lambda_expr)));
        
        // This should evaluate to 42
        let result = evaluator.eval(&spanned(call_cc_expr), env);
        
        match result {
            Ok(Value::Literal(Literal::ExactInteger(n))) => {
                assert_eq!(n, 42);
            }
            Ok(Value::Literal(Literal::InexactReal(n))) => {
                assert_eq!(n, 42.0);
            }
            Ok(other) => panic!("Expected number 42, got {other:?}"),
            Err(e) => panic!("Evaluation failed: {e:?}"),
        }
    }

    #[test]
    fn test_call_cc_with_continuation_invocation() {
        let mut evaluator = Evaluator::new();
        let env = Rc::new(Environment::new(None, 0));
        
        // Create: (call/cc (lambda (escape) (escape 42)))
        // This should return 42 by invoking the continuation
        let app_expr = Expr::Application {
            operator: Box::new(spanned(Expr::Identifier("escape".to_string()))),
            operands: vec![spanned(Expr::Literal(Literal::integer(42)))],
        };
        let lambda_expr = make_lambda("escape", app_expr);
        let call_cc_expr = Expr::CallCC(Box::new(spanned(lambda_expr)));
        
        let result = evaluator.eval(&spanned(call_cc_expr), env);
        
        // This test verifies the structure is correct, 
        // though the actual continuation invocation requires more complex setup
        match result {
            Ok(_) => {
                // If we get here, the call/cc structure was parsed and handled correctly
                // The exact result depends on the current implementation state
            }
            Err(e) => {
                // Check that it's not a parsing error but a runtime limitation
                let error_msg = format!("{e:?}");
                assert!(error_msg.contains("call/cc") || error_msg.contains("continuation") || error_msg.contains("escape"));
            }
        }
    }

    #[test]
    fn test_continuation_multiple_calls() {
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        let continuation = Arc::new(Continuation::new(
            vec![],
            env,
            1,
            None,
        ));
        
        let mut evaluator = Evaluator::new();
        
        // Under R7RS semantics, continuations can be called multiple times
        // First invocation should succeed
        let result1 = evaluator.call_continuation(continuation.clone(), Value::integer(42));
        match result1 {
            EvalStep::Return(Value::Literal(Literal::Number(n))) => {
                assert_eq!(n, 42.0);
            }
            other => panic!("Expected return of 42, got {other:?}"),
        }
        
        // Second invocation should now also succeed under R7RS semantics
        let result2 = evaluator.call_continuation(continuation, Value::integer(84));
        match result2 {
            EvalStep::Return(Value::Literal(Literal::Number(n))) => {
                assert_eq!(n, 84.0);
            }
            other => panic!("Expected return of 84, got {other:?}"),
        }
    }

    #[test]
    fn test_continuation_predicate() {
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        let continuation = Arc::new(Continuation::new(
            vec![],
            env,
            1,
            None,
        ));
        
        let cont_value = Value::Continuation(continuation);
        let non_cont_value = Value::integer(42);
        
        // Test continuation? with actual continuation
        let result1 = crate::stdlib::control::primitive_continuation_p(&[cont_value]);
        assert_eq!(result1.unwrap(), Value::boolean(true));
        
        // Test continuation? with non-continuation
        let result2 = crate::stdlib::control::primitive_continuation_p(&[non_cont_value]);
        assert_eq!(result2.unwrap(), Value::boolean(false));
    }

    #[test]
    fn test_multiple_frame_types() {
        let env = Arc::new(ThreadSafeEnvironment::new(None, 0));
        
        // Test different frame types can be created
        let _call_cc_frame = Frame::CallCC {
            environment: env.clone(),
            source: Span::default(),
        };
        
        let _proc_call_frame = Frame::ProcedureCall {
            procedure_name: Some("test".to_string()),
            remaining_body: vec![],
            environment: env.clone(),
            source: Span::default(),
        };
        
        let _app_frame = Frame::Application {
            operator: Value::integer(42),
            evaluated_args: vec![],
            remaining_args: vec![],
            environment: env.clone(),
            source: Span::default(),
        };
        
        // Just verify they can be constructed without panicking
        assert!(true);
    }

    #[test]
    fn test_call_cc_integration_with_special_form() {
        let mut evaluator = Evaluator::new();
        let env = Rc::new(Environment::new(None, 0));
        
        // Test that call/cc is recognized as a special form
        let identity_lambda = make_lambda("x", Expr::Identifier("x".to_string()));
        let call_cc_expr = Expr::CallCC(Box::new(spanned(identity_lambda)));
        
        // This should not fail due to "unknown special form"
        let result = evaluator.eval(&spanned(call_cc_expr), env);
        
        // We expect either success or a specific call/cc related error,
        // not a "unknown expression type" error
        match result {
            Ok(_) => {
                // Success is good
            }
            Err(e) => {
                let error_msg = format!("{e:?}");
                // Should not be an "unimplemented expression" error
                assert!(!error_msg.contains("Unimplemented expression type"));
            }
        }
    }
}