scheme-rs 0.1.0

Embedded scheme for the Rust ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
//! Scheme Procedures.
//!
//! Scheme procedures, more commonly known as [`closures`](https://en.wikipedia.org/wiki/Closure_(computer_programming))
//! as they capture their environment, are the fundamental and only way to
//! transfer control from a Rust context to a Scheme context.
//!
//! # Calling procedures from Rust
//!
//! # Manually creating closures
//!
//! Generally procedures are created in Scheme contexts. However, it is
//! occasionally desirable to create a closure in Rust contexts. This can be
//! done with a [`cps_bridge`] function and a call to [`Procedure::new`]. The
//! `env` argument to the CPS function is a reference to the vector passed to
//! the `new` function:
//!
//! ```
//! # use scheme_rs::{proc::{Procedure, BridgePtr, Application, DynamicState},
//! # registry::cps_bridge, value::Value, runtime::Runtime, exceptions::Exception};
//! #[cps_bridge]
//! fn closure(
//!     _runtime: &Runtime,
//!     env: &[Value],
//!     _args: &[Value],
//!     _rest_args: &[Value],
//!     _dyn_state: &mut DynamicState,
//!     k: Value,
//! ) -> Result<Application, Exception> {
//!     Ok(Application::new(k.try_into()?, vec![ env[0].clone() ]))
//! }
//!
//! # fn main() {
//! # let runtime = Runtime::new();
//! let closure = Procedure::new(
//!     runtime,
//!     vec![ Value::from(3.1415) ],
//!     closure as BridgePtr,
//!     0,
//!     false,
//! );
//! # }
//! ```
//!
//! By default the environment is immutable. If the environment needs to be
//! modified, a [`Cell`](scheme_rs::value::Cell) can be used:
//!
//! ```
//! # use scheme_rs::{
//! #     proc::{Procedure, BridgePtr, Application, DynamicState},
//! #     registry::cps_bridge, value::{Value, Cell}, runtime::Runtime,
//! #     exceptions::Exception,
//! #     num::Number,
//! # };
//! #[cps_bridge]
//! fn next_num(
//!     _runtime: &Runtime,
//!     env: &[Value],
//!     _args: &[Value],
//!     _rest_args: &[Value],
//!     _dyn_state: &mut DynamicState,
//!     k: Value,
//! ) -> Result<Application, Exception> {
//!     // Fetch the cell from the environment:
//!     let cell: Cell = env[0].try_to_scheme_type()?;
//!     let curr: Number = cell.get().try_into()?;
//!
//!     // Increment the cell
//!     cell.set(Value::from(curr.clone() + Number::from(1)));
//!
//!     // Return the previous value:
//!     Ok(Application::new(k.try_into()?, vec![ Value::from(curr) ]))
//! }
//!
//! # fn main() {
//! # let runtime = Runtime::new();
//! let next_num = Procedure::new(
//!     runtime,
//!     // Cells must be converted to values:
//!     vec![ Value::from(Cell::new(Value::from(3.1415))) ],
//!     next_num as BridgePtr,
//!     0,
//!     false,
//! );
//! # }
//! ```
//!
//! # Categories of procedures
//!
//! In scheme-rs, procedures can be placed into a few different categories, the
//! most obvious is that procedures are either _user_ functions or
//! [_continuations_](https://en.wikipedia.org/wiki/Continuation). This
//! categorization is mostly transparent to the user.

use crate::{
    env::Local,
    exceptions::{Exception, raise},
    gc::{Gc, GcInner, Trace},
    lists::{self, Pair, list_to_vec},
    ports::{BufferMode, Port, Transcoder},
    records::{Record, RecordTypeDescriptor, SchemeCompatible, rtd},
    registry::BridgeFnDebugInfo,
    runtime::{Runtime, RuntimeInner},
    symbols::Symbol,
    syntax::Span,
    value::Value,
    vectors::Vector,
};
use parking_lot::RwLock;
use scheme_rs_macros::{cps_bridge, maybe_async, maybe_await};
use std::{
    collections::HashMap,
    fmt,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicUsize, Ordering},
    },
};

/// A function pointer to a generated continuation.
pub(crate) type ContinuationPtr = unsafe extern "C" fn(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application;

/// A function pointer to a generated user function.
pub(crate) type UserPtr = unsafe extern "C" fn(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    args: *const Value,
    dyn_state: *mut DynamicState,
    k: Value,
) -> *mut Application;

/// A function pointer to a sync Rust bridge function.
pub type BridgePtr = for<'a> fn(
    runtime: &'a Runtime,
    env: &'a [Value],
    // TODO: Make this a Vec
    args: &'a [Value],
    rest_args: &'a [Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Application;

/// A function pointer to an async Rust bridge function.
#[cfg(feature = "async")]
pub type AsyncBridgePtr = for<'a> fn(
    runtime: &'a Runtime,
    env: &'a [Value],
    args: &'a [Value],
    rest_args: &'a [Value],
    dyn_state: &'a mut DynamicState,
    k: Value,
) -> futures::future::BoxFuture<'a, Application>;

#[derive(Copy, Clone, Debug)]
pub(crate) enum FuncPtr {
    /// A function defined in Rust
    Bridge(BridgePtr),
    #[cfg(feature = "async")]
    /// An async function defined in Rust
    AsyncBridge(AsyncBridgePtr),
    /// A JIT compiled user function
    User(UserPtr),
    /// A JIT compiled (or occasionally defined in Rust) continuation
    Continuation(ContinuationPtr),
    /// A continuation that exits a prompt. Can be dynamically replaced
    PromptBarrier {
        barrier_id: usize,
        k: ContinuationPtr,
    },
}

impl From<BridgePtr> for FuncPtr {
    fn from(ptr: BridgePtr) -> Self {
        Self::Bridge(ptr)
    }
}

#[cfg(feature = "async")]
impl From<AsyncBridgePtr> for FuncPtr {
    fn from(ptr: AsyncBridgePtr) -> Self {
        Self::AsyncBridge(ptr)
    }
}

impl From<UserPtr> for FuncPtr {
    fn from(ptr: UserPtr) -> Self {
        Self::User(ptr)
    }
}

enum JitFuncPtr {
    Continuation(ContinuationPtr),
    User(UserPtr),
}

#[derive(Clone, Trace)]
#[repr(align(16))]
pub(crate) struct ProcedureInner {
    /// The runtime the Procedure is defined in. This is necessary to ensure that
    /// dropping the runtime does not de-allocate the function pointer for this
    /// procedure.
    // TODO: Do we make this optional in the case of bridge functions?
    pub(crate) runtime: Runtime,
    /// Environmental variables used by the procedure.
    pub(crate) env: Vec<Value>,
    /// Fuction pointer to the body of the procecure.
    #[trace(skip)]
    pub(crate) func: FuncPtr,
    /// Number of required arguments to this procedure.
    pub(crate) num_required_args: usize,
    /// Whether or not this is a variadic function.
    pub(crate) variadic: bool,
    /// Whether or not this function is a variable transformer.
    pub(crate) is_variable_transformer: bool,
    /// Debug information for this function. Only applicable if the function is
    /// a user function, i.e. not a continuation.
    pub(crate) debug_info: Option<Arc<ProcDebugInfo>>,
}

impl ProcedureInner {
    pub(crate) fn new(
        runtime: Runtime,
        env: Vec<Value>,
        func: FuncPtr,
        num_required_args: usize,
        variadic: bool,
        debug_info: Option<Arc<ProcDebugInfo>>,
    ) -> Self {
        Self {
            runtime,
            env,
            func,
            num_required_args,
            variadic,
            is_variable_transformer: false,
            debug_info,
        }
    }

    pub fn is_continuation(&self) -> bool {
        matches!(
            self.func,
            FuncPtr::Continuation(_) | FuncPtr::PromptBarrier { .. }
        )
    }

    pub(crate) fn prepare_args(
        &self,
        mut args: Vec<Value>,
        dyn_state: &mut DynamicState,
    ) -> Result<(Vec<Value>, Option<Value>), Application> {
        // Extract the continuation, if it is required
        let cont = (!self.is_continuation()).then(|| args.pop().unwrap());

        // Error if the number of arguments provided is incorrect
        if args.len() < self.num_required_args {
            return Err(raise(
                self.runtime.clone(),
                Exception::wrong_num_of_args(self.num_required_args, args.len()).into(),
                dyn_state,
            ));
        }

        if !self.variadic && args.len() > self.num_required_args {
            return Err(raise(
                self.runtime.clone(),
                Exception::wrong_num_of_args(self.num_required_args, args.len()).into(),
                dyn_state,
            ));
        }

        Ok((args, cont))
    }

    #[cfg(feature = "async")]
    async fn apply_async_bridge(
        &self,
        func: AsyncBridgePtr,
        args: &[Value],
        dyn_state: &mut DynamicState,
        k: Value,
    ) -> Application {
        let (args, rest_args) = if self.variadic {
            args.split_at(self.num_required_args)
        } else {
            (args, &[] as &[Value])
        };

        (func)(&self.runtime, &self.env, args, rest_args, dyn_state, k).await
    }

    fn apply_sync_bridge(
        &self,
        func: BridgePtr,
        args: &[Value],
        dyn_state: &mut DynamicState,
        k: Value,
    ) -> Application {
        let (args, rest_args) = if self.variadic {
            args.split_at(self.num_required_args)
        } else {
            (args, &[] as &[Value])
        };

        (func)(&self.runtime, &self.env, args, rest_args, dyn_state, k)
    }

    fn apply_jit(
        &self,
        func: JitFuncPtr,
        mut args: Vec<Value>,
        dyn_state: &mut DynamicState,
        k: Option<Value>,
    ) -> Application {
        if self.variadic {
            let mut rest_args = Value::null();
            let extra_args = args.len() - self.num_required_args;
            for _ in 0..extra_args {
                rest_args = Value::from(Pair::new(args.pop().unwrap(), rest_args, false));
            }
            args.push(rest_args);
        }

        let app = match func {
            JitFuncPtr::Continuation(sync_fn) => unsafe {
                (sync_fn)(
                    Gc::as_ptr(&self.runtime.0),
                    self.env.as_ptr(),
                    args.as_ptr(),
                    dyn_state as *mut DynamicState,
                )
            },
            JitFuncPtr::User(sync_fn) => unsafe {
                (sync_fn)(
                    Gc::as_ptr(&self.runtime.0),
                    self.env.as_ptr(),
                    args.as_ptr(),
                    dyn_state as *mut DynamicState,
                    Value::from_raw(Value::as_raw(k.as_ref().unwrap())),
                )
            },
        };

        unsafe { *Box::from_raw(app) }
    }

    /// Apply the arguments to the function, returning the next application.
    #[maybe_async]
    pub fn apply(&self, args: Vec<Value>, dyn_state: &mut DynamicState) -> Application {
        if let FuncPtr::PromptBarrier { barrier_id: id, .. } = self.func {
            dyn_state.pop_marks();
            match dyn_state.pop_dyn_stack() {
                Some(DynStackElem::PromptBarrier(PromptBarrier {
                    barrier_id,
                    replaced_k,
                })) if barrier_id == id => {
                    let (args, _) = match replaced_k.0.prepare_args(args, dyn_state) {
                        Ok(args) => args,
                        Err(raised) => return raised,
                    };
                    return Application::new(replaced_k, args);
                }
                Some(other) => dyn_state.push_dyn_stack(other),
                _ => (),
            }
        }

        let (args, k) = match self.prepare_args(args, dyn_state) {
            Ok(args) => args,
            Err(raised) => return raised,
        };

        match self.func {
            FuncPtr::Bridge(sbridge) => {
                self.apply_sync_bridge(sbridge, &args, dyn_state, k.unwrap())
            }
            #[cfg(feature = "async")]
            FuncPtr::AsyncBridge(abridge) => {
                self.apply_async_bridge(abridge, &args, dyn_state, k.unwrap())
                    .await
            }
            FuncPtr::User(user) => self.apply_jit(JitFuncPtr::User(user), args, dyn_state, k),
            FuncPtr::Continuation(k) => {
                dyn_state.pop_marks();
                self.apply_jit(JitFuncPtr::Continuation(k), args, dyn_state, None)
            }
            FuncPtr::PromptBarrier { k, .. } => {
                self.apply_jit(JitFuncPtr::Continuation(k), args, dyn_state, None)
            }
        }
    }

    #[cfg(feature = "async")]
    /// Attempt to call the function, and throw an error if is async
    pub fn apply_sync(&self, args: Vec<Value>, dyn_state: &mut DynamicState) -> Application {
        if let FuncPtr::PromptBarrier { barrier_id: id, .. } = self.func {
            dyn_state.pop_marks();
            match dyn_state.pop_dyn_stack() {
                Some(DynStackElem::PromptBarrier(PromptBarrier {
                    barrier_id,
                    replaced_k,
                })) if barrier_id == id => {
                    let (args, _) = match replaced_k.0.prepare_args(args, dyn_state) {
                        Ok(args) => args,
                        Err(raised) => return raised,
                    };
                    return Application::new(replaced_k, args);
                }
                Some(other) => dyn_state.push_dyn_stack(other),
                _ => (),
            }
        }

        let (args, k) = match self.prepare_args(args, dyn_state) {
            Ok(args) => args,
            Err(raised) => return raised,
        };

        match self.func {
            FuncPtr::Bridge(sbridge) => {
                self.apply_sync_bridge(sbridge, &args, dyn_state, k.unwrap())
            }
            FuncPtr::AsyncBridge(_) => raise(
                self.runtime.clone(),
                Exception::error("attempt to apply async function in a sync-only context").into(),
                dyn_state,
            ),
            FuncPtr::User(user) => self.apply_jit(JitFuncPtr::User(user), args, dyn_state, k),
            FuncPtr::Continuation(k) => {
                dyn_state.pop_marks();
                self.apply_jit(JitFuncPtr::Continuation(k), args, dyn_state, None)
            }
            FuncPtr::PromptBarrier { k, .. } => {
                self.apply_jit(JitFuncPtr::Continuation(k), args, dyn_state, None)
            }
        }
    }
}

impl fmt::Debug for ProcedureInner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_continuation() {
            return write!(f, "continuation");
        }

        let Some(ref debug_info) = self.debug_info else {
            write!(f, "(<lambda>")?;
            for i in 0..self.num_required_args {
                write!(f, " ${i}")?;
            }
            if self.variadic {
                write!(f, " . ${}", self.num_required_args)?;
            }
            return write!(f, ")");
        };

        write!(f, "({}", debug_info.name)?;

        if let Some((last, args)) = debug_info.args.split_last() {
            for arg in args {
                write!(f, " {arg}")?;
            }
            if self.variadic {
                write!(f, " .")?;
            }
            write!(f, " {last}")?;
        }

        write!(f, ") at {}", debug_info.location)
    }
}

/// The runtime representation of a Procedure, which can be either a user
/// function or a continuation. Contains a reference to all of the environmental
/// variables used in the body, along with a function pointer to the body of the
/// procedure.
#[derive(Clone, Trace)]
pub struct Procedure(pub(crate) Gc<ProcedureInner>);

impl Procedure {
    #[allow(private_bounds)]
    /// Creates a new procedure. `func` must be a [`BridgePtr`] or an
    /// `AsyncBridgePtr` if `async` is enabled.
    pub fn new(
        runtime: Runtime,
        env: Vec<Value>,
        func: impl Into<FuncPtr>,
        num_required_args: usize,
        variadic: bool,
    ) -> Self {
        Self::with_debug_info(runtime, env, func.into(), num_required_args, variadic, None)
    }

    pub(crate) fn with_debug_info(
        runtime: Runtime,
        env: Vec<Value>,
        func: FuncPtr,
        num_required_args: usize,
        variadic: bool,
        debug_info: Option<Arc<ProcDebugInfo>>,
    ) -> Self {
        Self(Gc::new(ProcedureInner {
            runtime,
            env,
            func,
            num_required_args,
            variadic,
            is_variable_transformer: false,
            debug_info,
        }))
    }

    /// Get the runtime associated with the procedure
    pub fn get_runtime(&self) -> Runtime {
        self.0.runtime.clone()
    }

    /// Return the number of required arguments and whether or not this function
    /// is variadic
    pub fn get_formals(&self) -> (usize, bool) {
        (self.0.num_required_args, self.0.variadic)
    }

    /// Return the debug information associated with procedure, if it exists.
    pub fn get_debug_info(&self) -> Option<Arc<ProcDebugInfo>> {
        self.0.debug_info.clone()
    }

    /// # Safety
    /// `args` must be a valid pointer and contain num_required_args + variadic entries.
    pub(crate) unsafe fn collect_args(&self, args: *const Value) -> Vec<Value> {
        // I don't really like this, but what are you gonna do?
        let (num_required_args, variadic) = self.get_formals();

        unsafe {
            let mut collected_args: Vec<_> = (0..num_required_args)
                .map(|i| args.add(i).as_ref().unwrap().clone())
                .collect();

            if variadic {
                let rest_args = args.add(num_required_args).as_ref().unwrap().clone();
                let mut vec = Vec::new();
                lists::list_to_vec(&rest_args, &mut vec);
                collected_args.extend(vec);
            }

            collected_args
        }
    }

    pub fn is_variable_transformer(&self) -> bool {
        self.0.is_variable_transformer
    }

    /// Return whether or not the procedure is a continuation
    pub fn is_continuation(&self) -> bool {
        self.0.is_continuation()
    }

    /// Applies `args` to the procedure and returns the values it evaluates to.
    #[maybe_async]
    pub fn call(&self, args: &[Value]) -> Result<Vec<Value>, Exception> {
        let mut args = args.to_vec();

        args.push(halt_continuation(self.get_runtime()));

        maybe_await!(Application::new(self.clone(), args).eval(&mut DynamicState::default()))
    }

    #[cfg(feature = "async")]
    pub fn call_sync(&self, args: &[Value]) -> Result<Vec<Value>, Exception> {
        let mut args = args.to_vec();

        args.push(halt_continuation(self.get_runtime()));

        Application::new(self.clone(), args).eval_sync(&mut DynamicState::default())
    }
}

static HALT_CONTINUATION: OnceLock<Value> = OnceLock::new();

/// Return a continuation that returns its expressions to the Rust program.
pub fn halt_continuation(runtime: Runtime) -> Value {
    unsafe extern "C" fn halt(
        _runtime: *mut GcInner<RwLock<RuntimeInner>>,
        _env: *const Value,
        args: *const Value,
        _dyn_state: *mut DynamicState,
    ) -> *mut Application {
        unsafe { crate::runtime::halt(Value::into_raw(args.read())) }
    }

    HALT_CONTINUATION
        .get_or_init(move || {
            Value::from(Procedure(Gc::new(ProcedureInner::new(
                runtime,
                Vec::new(),
                FuncPtr::Continuation(halt),
                0,
                true,
                None,
            ))))
        })
        .clone()
}

impl fmt::Debug for Procedure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl PartialEq for Procedure {
    fn eq(&self, rhs: &Procedure) -> bool {
        Gc::ptr_eq(&self.0, &rhs.0)
    }
}

pub(crate) enum OpType {
    Proc(Procedure),
    HaltOk,
    HaltErr,
}

/// An application of a function to a given set of values.
pub struct Application {
    /// The operator being applied to.
    op: OpType,
    /// The arguments being applied to the operator.
    args: Vec<Value>,
}

impl Application {
    pub fn new(op: Procedure, args: Vec<Value>) -> Self {
        Self {
            op: OpType::Proc(op),
            args,
        }
    }

    pub fn halt_ok(args: Vec<Value>) -> Self {
        Self {
            op: OpType::HaltOk,
            args,
        }
    }

    pub fn halt_err(arg: Value) -> Self {
        Self {
            op: OpType::HaltErr,
            args: vec![arg],
        }
    }

    /// Evaluate the application - and all subsequent application - until all that
    /// remains are values. This is the main trampoline of the evaluation engine.
    #[maybe_async]
    pub fn eval(mut self, dyn_state: &mut DynamicState) -> Result<Vec<Value>, Exception> {
        loop {
            let op = match self.op {
                OpType::Proc(proc) => proc,
                OpType::HaltOk => return Ok(self.args),
                OpType::HaltErr => {
                    return Err(Exception(self.args.pop().unwrap()));
                }
            };
            self = maybe_await!(op.0.apply(self.args, dyn_state));
        }
    }

    #[cfg(feature = "async")]
    /// Just like [eval] but throws an error if we encounter an async function.
    pub fn eval_sync(mut self, dyn_state: &mut DynamicState) -> Result<Vec<Value>, Exception> {
        loop {
            let op = match self.op {
                OpType::Proc(proc) => proc,
                OpType::HaltOk => return Ok(self.args),
                OpType::HaltErr => {
                    return Err(Exception(self.args.pop().unwrap()));
                }
            };
            self = op.0.apply_sync(self.args, dyn_state);
        }
    }
}

/// Debug information associated with a procedure, including its name, argument
/// names, and source location.
#[derive(Debug)]
pub struct ProcDebugInfo {
    /// The name of the function.
    pub name: Symbol,
    /// Named arguments for the function.
    pub args: Vec<Local>,
    /// Location of the function definition
    pub location: Span,
}

impl ProcDebugInfo {
    pub fn new(name: Option<Symbol>, args: Vec<Local>, location: Span) -> Self {
        Self {
            name: name.unwrap_or_else(|| Symbol::intern("<lambda>")),
            args,
            location,
        }
    }

    pub fn from_bridge_fn(name: &'static str, debug_info: BridgeFnDebugInfo) -> Self {
        Self {
            name: Symbol::intern(name),
            args: debug_info
                .args
                .iter()
                .map(|arg| Local::gensym_with_name(Symbol::intern(arg)))
                .collect(),
            location: Span {
                line: debug_info.line,
                column: debug_info.column as usize,
                offset: debug_info.offset,
                file: std::sync::Arc::new(debug_info.file.to_string()),
            },
        }
    }
}

#[cps_bridge(def = "apply arg1 . args", lib = "(rnrs base builtins (6))")]
pub fn apply(
    _runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    rest_args: &[Value],
    _dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    if rest_args.is_empty() {
        return Err(Exception::wrong_num_of_args(2, args.len()));
    }
    let op: Procedure = args[0].clone().try_into()?;
    let (last, args) = rest_args.split_last().unwrap();
    let mut args = args.to_vec();
    list_to_vec(last, &mut args);
    args.push(k);
    Ok(Application::new(op.clone(), args))
}

////////////////////////////////////////////////////////////////////////////////
//
// Dynamic state
//

/// The dynamic state of the running program, including winders, exception
/// handlers, and continuation marks.
#[derive(Clone, Debug, Trace)]
pub struct DynamicState {
    dyn_stack: Vec<DynStackElem>,
    cont_marks: Vec<HashMap<Symbol, Value>>,
}

impl DynamicState {
    pub fn new() -> Self {
        Self {
            dyn_stack: Vec::new(),
            // Procedures returned by the JIT compiler are delimited
            // continuations (of sorts), and therefore we need to preallocate
            // the initial marks for them since there's no mechanism to allocate
            // for them when they're run.
            cont_marks: vec![HashMap::new()],
        }
    }

    /// This is the only method you can use to create continuations, in order to
    /// ensure that a continuation isn't allocated without a corresponding push
    /// to cont_marks
    pub(crate) fn new_k(
        &mut self,
        runtime: Runtime,
        env: Vec<Value>,
        k: ContinuationPtr,
        num_required_args: usize,
        variadic: bool,
    ) -> Procedure {
        self.push_marks();
        Procedure::with_debug_info(
            runtime,
            env,
            FuncPtr::Continuation(k),
            num_required_args,
            variadic,
            None,
        )
    }

    pub(crate) fn push_marks(&mut self) {
        self.cont_marks.push(HashMap::new());
    }

    pub(crate) fn pop_marks(&mut self) {
        self.cont_marks.pop();
    }

    pub(crate) fn current_marks(&self, tag: Symbol) -> Vec<Value> {
        self.cont_marks
            .iter()
            .rev()
            .flat_map(|marks| marks.get(&tag).cloned())
            .collect()
    }

    pub(crate) fn set_continuation_mark(&mut self, tag: Symbol, val: Value) {
        self.cont_marks.last_mut().unwrap().insert(tag, val);
    }

    // TODO: We should certainly try to optimize these functions. Linear
    // searching isn't _great_, although in practice I can't imagine this stack
    // will ever get very large.

    pub fn current_exception_handler(&self) -> Option<Procedure> {
        self.dyn_stack.iter().rev().find_map(|elem| match elem {
            DynStackElem::ExceptionHandler(proc) => Some(proc.clone()),
            _ => None,
        })
    }

    pub fn current_input_port(&self) -> Port {
        self.dyn_stack
            .iter()
            .rev()
            .find_map(|elem| match elem {
                DynStackElem::CurrentInputPort(port) => Some(port.clone()),
                _ => None,
            })
            .unwrap_or_else(|| {
                Port::new(
                    "<stdin>",
                    #[cfg(not(feature = "async"))]
                    std::io::stdin(),
                    #[cfg(feature = "tokio")]
                    tokio::io::stdin(),
                    BufferMode::Line,
                    Some(Transcoder::native()),
                )
            })
    }

    pub fn current_output_port(&self) -> Port {
        self.dyn_stack
            .iter()
            .rev()
            .find_map(|elem| match elem {
                DynStackElem::CurrentOutputPort(port) => Some(port.clone()),
                _ => None,
            })
            .unwrap_or_else(|| {
                Port::new(
                    "<stdout>",
                    #[cfg(not(feature = "async"))]
                    std::io::stdout(),
                    #[cfg(feature = "tokio")]
                    tokio::io::stdout(),
                    // TODO: Probably should change this to line, but that
                    // doesn't play nicely with rustyline
                    BufferMode::None,
                    Some(Transcoder::native()),
                )
            })
    }

    pub(crate) fn push_dyn_stack(&mut self, elem: DynStackElem) {
        self.dyn_stack.push(elem);
    }

    pub(crate) fn pop_dyn_stack(&mut self) -> Option<DynStackElem> {
        self.dyn_stack.pop()
    }

    pub(crate) fn dyn_stack_get(&self, idx: usize) -> Option<&DynStackElem> {
        self.dyn_stack.get(idx)
    }

    pub(crate) fn dyn_stack_last(&self) -> Option<&DynStackElem> {
        self.dyn_stack.last()
    }

    pub(crate) fn dyn_stack_len(&self) -> usize {
        self.dyn_stack.len()
    }

    pub(crate) fn dyn_stack_is_empty(&self) -> bool {
        self.dyn_stack.is_empty()
    }
}

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

impl SchemeCompatible for DynamicState {
    fn rtd() -> Arc<RecordTypeDescriptor> {
        rtd!(name: "$dyn-stack", sealed: true, opaque: true)
    }
}

#[derive(Clone, Debug, PartialEq, Trace)]
pub(crate) enum DynStackElem {
    Prompt(Prompt),
    PromptBarrier(PromptBarrier),
    Winder(Winder),
    ExceptionHandler(Procedure),
    CurrentInputPort(Port),
    CurrentOutputPort(Port),
}

pub(crate) unsafe extern "C" fn pop_dyn_stack(
    _runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the continuation
        let k: Procedure = env.as_ref().unwrap().clone().try_into().unwrap();

        dyn_state.as_mut().unwrap_unchecked().pop_dyn_stack();

        let args = k.collect_args(args);
        let app = Application::new(k, args);

        Box::into_raw(Box::new(app))
    }
}

#[cps_bridge(def = "print-trace", lib = "(rnrs base builtins (6))")]
pub fn print_trace(
    _runtime: &Runtime,
    _env: &[Value],
    _args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    println!(
        "trace: {:#?}",
        dyn_state.current_marks(Symbol::intern("trace"))
    );
    Ok(Application::new(k.try_into()?, vec![]))
}

////////////////////////////////////////////////////////////////////////////////
//
// Call with current continuation
//

#[cps_bridge(
    def = "call-with-current-continuation proc",
    lib = "(rnrs base builtins (6))"
)]
pub fn call_with_current_continuation(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [proc] = args else { unreachable!() };
    let proc: Procedure = proc.clone().try_into()?;

    let (req_args, variadic) = {
        let k: Procedure = k.clone().try_into()?;
        k.get_formals()
    };

    let dyn_state = Value::from(Record::from_rust_type(dyn_state.clone()));

    let escape_procedure = Procedure::new(
        runtime.clone(),
        vec![k.clone(), dyn_state],
        FuncPtr::Bridge(escape_procedure),
        req_args,
        variadic,
    );

    let app = Application::new(proc, vec![Value::from(escape_procedure), k]);

    Ok(app)
}

/// Prepare the continuation for call/cc. Clones the continuation environment
/// and creates a closure that calls the appropriate winders.
#[cps_bridge]
fn escape_procedure(
    runtime: &Runtime,
    env: &[Value],
    args: &[Value],
    rest_args: &[Value],
    dyn_state: &mut DynamicState,
    _k: Value,
) -> Result<Application, Exception> {
    // env[0] is the continuation
    let k = env[0].clone();

    // env[1] is the dyn stack of the continuation
    let saved_dyn_state_val = env[1].clone();
    let saved_dyn_state = saved_dyn_state_val
        .try_to_rust_type::<DynamicState>()
        .unwrap();
    let saved_dyn_state_read = saved_dyn_state.as_ref();
    dyn_state.cont_marks = saved_dyn_state_read.cont_marks.clone();

    // Clone the continuation
    let k: Procedure = k.try_into().unwrap();

    let args = args.iter().chain(rest_args).cloned().collect::<Vec<_>>();

    // Simple optimization: check if we're in the same dyn stack
    if dyn_state.dyn_stack_len() == saved_dyn_state_read.dyn_stack_len()
        && dyn_state.dyn_stack_last() == saved_dyn_state_read.dyn_stack_last()
    {
        Ok(Application::new(k, args))
    } else {
        let args = Value::from(args);
        let k = dyn_state.new_k(
            runtime.clone(),
            vec![Value::from(k), args, saved_dyn_state_val],
            unwind,
            0,
            false,
        );
        Ok(Application::new(k, Vec::new()))
    }
}

unsafe extern "C" fn unwind(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the ultimate continuation
        let k = env.as_ref().unwrap().clone();

        // env[1] are the arguments to pass to k
        let args = env.add(1).as_ref().unwrap().clone();

        // env[2] is the stack we are trying to reach
        let dest_stack_val = env.add(2).as_ref().unwrap().clone();
        let dest_stack = dest_stack_val
            .clone()
            .try_to_rust_type::<DynamicState>()
            .unwrap();
        let dest_stack_read = dest_stack.as_ref();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();

        while !dyn_state.dyn_stack_is_empty()
            && (dyn_state.dyn_stack_len() > dest_stack_read.dyn_stack_len()
                || dyn_state.dyn_stack_last()
                    != dest_stack_read.dyn_stack_get(dyn_state.dyn_stack_len() - 1))
        {
            match dyn_state.pop_dyn_stack() {
                None => {
                    break;
                }
                Some(DynStackElem::Winder(winder)) => {
                    // Call the out winder while unwinding
                    let app = Application::new(
                        winder.out_thunk,
                        vec![Value::from(dyn_state.new_k(
                            Runtime::from_raw_inc_rc(runtime),
                            vec![k, args, dest_stack_val],
                            unwind,
                            0,
                            false,
                        ))],
                    );
                    return Box::into_raw(Box::new(app));
                }
                _ => (),
            };
        }

        // Begin winding
        let app = Application::new(
            dyn_state.new_k(
                Runtime::from_raw_inc_rc(runtime),
                vec![k, args, dest_stack_val, Value::from(false)],
                wind,
                0,
                false,
            ),
            Vec::new(),
        );

        Box::into_raw(Box::new(app))
    }
}

unsafe extern "C" fn wind(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the ultimate continuation
        let k = env.as_ref().unwrap().clone();

        // env[1] are the arguments to pass to k
        let args = env.add(1).as_ref().unwrap().clone();

        // env[2] is the stack we are trying to reach
        let dest_stack_val = env.add(2).as_ref().unwrap().clone();
        let dest_stack = dest_stack_val.try_to_rust_type::<DynamicState>().unwrap();
        let dest_stack_read = dest_stack.as_ref();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();

        // env[3] is potentially a winder that we should push onto the dyn stack
        let winder = env.add(3).as_ref().unwrap().clone();
        if winder.is_true() {
            let winder = winder.try_to_rust_type::<Winder>().unwrap();
            dyn_state.push_dyn_stack(DynStackElem::Winder(winder.as_ref().clone()));
        }

        while dyn_state.dyn_stack_len() < dest_stack_read.dyn_stack_len() {
            match dest_stack_read
                .dyn_stack_get(dyn_state.dyn_stack_len())
                .cloned()
            {
                None => {
                    break;
                }
                Some(DynStackElem::Winder(winder)) => {
                    // Call the in winder while winding
                    let app = Application::new(
                        winder.in_thunk.clone(),
                        vec![Value::from(dyn_state.new_k(
                            Runtime::from_raw_inc_rc(runtime),
                            vec![
                                k,
                                args,
                                dest_stack_val,
                                Value::from(Record::from_rust_type(winder)),
                            ],
                            wind,
                            0,
                            false,
                        ))],
                    );
                    return Box::into_raw(Box::new(app));
                }
                Some(elem) => dyn_state.push_dyn_stack(elem),
            }
        }

        let args: Vector = args.try_into().unwrap();
        let args = args.0.vec.read().to_vec();

        Box::into_raw(Box::new(Application::new(k.try_into().unwrap(), args)))
    }
}

unsafe extern "C" fn call_consumer_with_values(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the consumer
        let consumer = env.as_ref().unwrap().clone();
        let type_name = consumer.type_name();

        let consumer: Procedure = match consumer.try_into() {
            Ok(consumer) => consumer,
            _ => {
                let raised = raise(
                    Runtime::from_raw_inc_rc(runtime),
                    Exception::invalid_operator(type_name).into(),
                    dyn_state.as_mut().unwrap_unchecked(),
                );
                return Box::into_raw(Box::new(raised));
            }
        };

        // env[1] is the continuation
        let k = env.add(1).as_ref().unwrap().clone();

        let mut collected_args: Vec<_> = (0..consumer.0.num_required_args)
            .map(|i| args.add(i).as_ref().unwrap().clone())
            .collect();

        // I hate this constant going back and forth from variadic to list. I have
        // to figure out a way to make it consistent
        if consumer.0.variadic {
            let rest_args = args
                .add(consumer.0.num_required_args)
                .as_ref()
                .unwrap()
                .clone();
            let mut vec = Vec::new();
            list_to_vec(&rest_args, &mut vec);
            collected_args.extend(vec);
        }

        collected_args.push(k);

        Box::into_raw(Box::new(Application::new(consumer.clone(), collected_args)))
    }
}

#[cps_bridge(
    def = "call-with-values producer consumer",
    lib = "(rnrs base builtins (6))"
)]
pub fn call_with_values(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [producer, consumer] = args else {
        return Err(Exception::wrong_num_of_args(2, args.len()));
    };

    let producer: Procedure = producer.clone().try_into()?;
    let consumer: Procedure = consumer.clone().try_into()?;

    // Get the details of the consumer:
    let (num_required_args, variadic) = { (consumer.0.num_required_args, consumer.0.variadic) };

    let call_consumer_closure = dyn_state.new_k(
        runtime.clone(),
        vec![Value::from(consumer), k],
        call_consumer_with_values,
        num_required_args,
        variadic,
    );

    Ok(Application::new(
        producer,
        vec![Value::from(call_consumer_closure)],
    ))
}

////////////////////////////////////////////////////////////////////////////////
//
// Dynamic wind
//

#[derive(Clone, Debug, Trace, PartialEq)]
pub(crate) struct Winder {
    pub(crate) in_thunk: Procedure,
    pub(crate) out_thunk: Procedure,
}

impl SchemeCompatible for Winder {
    fn rtd() -> Arc<RecordTypeDescriptor> {
        rtd!(name: "$winder", sealed: true, opaque: true)
    }
}

#[cps_bridge(def = "dynamic-wind in body out", lib = "(rnrs base builtins (6))")]
pub fn dynamic_wind(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [in_thunk_val, body_thunk_val, out_thunk_val] = args else {
        return Err(Exception::wrong_num_of_args(3, args.len()));
    };

    let in_thunk: Procedure = in_thunk_val.clone().try_into()?;
    let _: Procedure = body_thunk_val.clone().try_into()?;

    let call_body_thunk_cont = dyn_state.new_k(
        runtime.clone(),
        vec![
            in_thunk_val.clone(),
            body_thunk_val.clone(),
            out_thunk_val.clone(),
            k,
        ],
        call_body_thunk,
        0,
        true,
    );

    Ok(Application::new(
        in_thunk,
        vec![Value::from(call_body_thunk_cont)],
    ))
}

pub(crate) unsafe extern "C" fn call_body_thunk(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the in thunk
        let in_thunk = env.as_ref().unwrap().clone();

        // env[1] is the body thunk
        let body_thunk: Procedure = env.add(1).as_ref().unwrap().clone().try_into().unwrap();

        // env[2] is the out thunk
        let out_thunk = env.add(2).as_ref().unwrap().clone();

        // env[3] is k, the continuation
        let k = env.add(3).as_ref().unwrap().clone();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();

        dyn_state.push_dyn_stack(DynStackElem::Winder(Winder {
            in_thunk: in_thunk.clone().try_into().unwrap(),
            out_thunk: out_thunk.clone().try_into().unwrap(),
        }));

        let k = dyn_state.new_k(
            Runtime::from_raw_inc_rc(runtime),
            vec![out_thunk, k],
            call_out_thunks,
            0,
            true,
        );

        let app = Application::new(body_thunk, vec![Value::from(k)]);

        Box::into_raw(Box::new(app))
    }
}

pub(crate) unsafe extern "C" fn call_out_thunks(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the out thunk
        let out_thunk: Procedure = env.as_ref().unwrap().clone().try_into().unwrap();

        // env[1] is k, the remaining continuation
        let k = env.add(1).as_ref().unwrap().clone();

        // args[0] is the result of the body thunk
        let body_thunk_res = args.as_ref().unwrap().clone();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();
        dyn_state.pop_dyn_stack();

        let cont = dyn_state.new_k(
            Runtime::from_raw_inc_rc(runtime),
            vec![body_thunk_res, k],
            forward_body_thunk_result,
            0,
            true,
        );

        let app = Application::new(out_thunk, vec![Value::from(cont)]);

        Box::into_raw(Box::new(app))
    }
}

unsafe extern "C" fn forward_body_thunk_result(
    _runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    _dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the result of the body thunk
        let body_thunk_res = env.as_ref().unwrap().clone();
        // env[1] is k, the continuation.
        let k: Procedure = env.add(1).as_ref().unwrap().clone().try_into().unwrap();

        let mut args = Vec::new();
        list_to_vec(&body_thunk_res, &mut args);

        Box::into_raw(Box::new(Application::new(k, args)))
    }
}

////////////////////////////////////////////////////////////////////////////////
//
// Prompts and delimited continuations
//

#[derive(Clone, Debug, PartialEq, Trace)]
pub(crate) struct Prompt {
    tag: Symbol,
    barrier_id: usize,
    handler: Procedure,
    handler_k: Procedure,
}

#[derive(Clone, Debug, PartialEq, Trace)]
pub(crate) struct PromptBarrier {
    barrier_id: usize,
    replaced_k: Procedure,
}

static BARRIER_ID: AtomicUsize = AtomicUsize::new(0);

#[cps_bridge(def = "call-with-prompt tag thunk handler", lib = "(prompts)")]
pub fn call_with_prompt(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [tag, thunk, handler] = args else {
        unreachable!()
    };

    let k_proc: Procedure = k.clone().try_into().unwrap();
    let (req_args, variadic) = k_proc.get_formals();
    let tag: Symbol = tag.clone().try_into().unwrap();

    let barrier_id = BARRIER_ID.fetch_add(1, Ordering::Relaxed);

    dyn_state.push_dyn_stack(DynStackElem::Prompt(Prompt {
        tag,
        handler: handler.clone().try_into().unwrap(),
        barrier_id,
        handler_k: k.clone().try_into()?,
    }));

    dyn_state.push_marks();

    let prompt_barrier = Procedure::new(
        runtime.clone(),
        vec![k],
        FuncPtr::PromptBarrier {
            barrier_id,
            k: pop_dyn_stack,
        },
        req_args,
        variadic,
    );

    Ok(Application::new(
        thunk.clone().try_into().unwrap(),
        vec![Value::from(prompt_barrier)],
    ))
}

#[cps_bridge(def = "abort-to-prompt tag", lib = "(prompts)")]
pub fn abort_to_prompt(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [tag] = args else { unreachable!() };

    let unwind_to_prompt = dyn_state.new_k(
        runtime.clone(),
        vec![
            k,
            tag.clone(),
            Value::from(Record::from_rust_type(dyn_state.clone())),
        ],
        unwind_to_prompt,
        0,
        false,
    );

    Ok(Application::new(unwind_to_prompt, Vec::new()))
}

unsafe extern "C" fn unwind_to_prompt(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is continuation
        let k = env.as_ref().unwrap().clone();
        // env[1] is the prompt tag
        let tag: Symbol = env.add(1).as_ref().unwrap().clone().try_into().unwrap();
        // env[2] is the saved dyn stack
        let saved_dyn_state = env.add(2).as_ref().unwrap().clone();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();

        loop {
            let app = match dyn_state.pop_dyn_stack() {
                None => {
                    // If the stack is empty, we should return the error
                    Application::halt_err(Value::from(Exception::error(format!(
                        "No prompt tag {tag} found"
                    ))))
                }
                Some(DynStackElem::Prompt(Prompt {
                    tag: prompt_tag,
                    barrier_id,
                    handler,
                    handler_k,
                })) if prompt_tag == tag => {
                    let saved_dyn_state =
                        saved_dyn_state.try_to_rust_type::<DynamicState>().unwrap();
                    let prompt_delimited_dyn_state = DynamicState {
                        dyn_stack: saved_dyn_state.as_ref().dyn_stack
                            [dyn_state.dyn_stack_len() + 1..]
                            .to_vec(),
                        cont_marks: saved_dyn_state.cont_marks.clone(),
                    };
                    let (req_args, var) = {
                        let k_proc: Procedure = k.clone().try_into().unwrap();
                        k_proc.get_formals()
                    };
                    Application::new(
                        handler,
                        vec![
                            Value::from(Procedure::new(
                                Runtime::from_raw_inc_rc(runtime),
                                vec![
                                    k,
                                    Value::from(barrier_id),
                                    Value::from(Record::from_rust_type(prompt_delimited_dyn_state)),
                                ],
                                FuncPtr::Bridge(delimited_continuation),
                                req_args,
                                var,
                            )),
                            Value::from(handler_k),
                        ],
                    )
                }
                Some(DynStackElem::Winder(winder)) => {
                    // If this is a winder, we should call the out winder while unwinding
                    Application::new(
                        winder.out_thunk,
                        vec![Value::from(dyn_state.new_k(
                            Runtime::from_raw_inc_rc(runtime),
                            vec![k, Value::from(tag), saved_dyn_state],
                            unwind_to_prompt,
                            0,
                            false,
                        ))],
                    )
                }
                _ => continue,
            };
            return Box::into_raw(Box::new(app));
        }
    }
}

#[cps_bridge]
fn delimited_continuation(
    runtime: &Runtime,
    env: &[Value],
    args: &[Value],
    rest_args: &[Value],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    // env[0] is the delimited continuation
    let dk = env[0].clone();

    // env[1] is the barrier Id
    let barrier_id: usize = env[1].try_to_scheme_type()?;

    // env[2] is the dyn stack of the continuation
    let saved_dyn_state_val = env[2].clone();
    let saved_dyn_state = saved_dyn_state_val
        .try_to_rust_type::<DynamicState>()
        .unwrap();
    let saved_dyn_state_read = saved_dyn_state.as_ref();
    // Restore continuation marks
    dyn_state.cont_marks = saved_dyn_state_read.cont_marks.clone();

    let args = args.iter().chain(rest_args).cloned().collect::<Vec<_>>();

    dyn_state.push_dyn_stack(DynStackElem::PromptBarrier(PromptBarrier {
        barrier_id,
        replaced_k: k.try_into()?,
    }));

    // Simple optimization: if the saved dyn stack is empty, we
    // can just call the delimited continuation
    if saved_dyn_state_read.dyn_stack_is_empty() {
        Ok(Application::new(dk.try_into()?, args))
    } else {
        let args = Value::from(args);
        let k = dyn_state.new_k(
            runtime.clone(),
            vec![
                dk,
                args,
                saved_dyn_state_val,
                Value::from(0),
                Value::from(false),
            ],
            wind_delim,
            0,
            false,
        );
        Ok(Application::new(k, Vec::new()))
    }
}

unsafe extern "C" fn wind_delim(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the ultimate continuation
        let k = env.as_ref().unwrap().clone();

        // env[1] are the arguments to pass to k
        let args = env.add(1).as_ref().unwrap().clone();

        // env[2] is the stack we are trying to reach
        let dest_stack_val = env.add(2).as_ref().unwrap().clone();
        let dest_stack = dest_stack_val.try_to_rust_type::<DynamicState>().unwrap();
        let dest_stack_read = dest_stack.as_ref();

        // env[3] is the index into the dest stack we're at
        let mut idx: usize = env.add(3).as_ref().unwrap().cast_to_scheme_type().unwrap();

        let dyn_state = dyn_state.as_mut().unwrap_unchecked();

        // env[4] is potentially a winder that we should push onto the dyn stack
        let winder = env.add(4).as_ref().unwrap().clone();
        if winder.is_true() {
            let winder = winder.try_to_rust_type::<Winder>().unwrap();
            dyn_state.push_dyn_stack(DynStackElem::Winder(winder.as_ref().clone()));
        }

        while let Some(elem) = dest_stack_read.dyn_stack_get(idx) {
            idx += 1;

            if let DynStackElem::Winder(winder) = elem {
                // Call the in winder while winding
                let app = Application::new(
                    winder.in_thunk.clone(),
                    vec![Value::from(dyn_state.new_k(
                        Runtime::from_raw_inc_rc(runtime),
                        vec![
                            k,
                            args,
                            dest_stack_val,
                            Value::from(Record::from_rust_type(winder.clone())),
                        ],
                        wind,
                        0,
                        false,
                    ))],
                );
                return Box::into_raw(Box::new(app));
            }
            dyn_state.push_dyn_stack(elem.clone());
        }

        let args: Vector = args.try_into().unwrap();
        let args = args.0.vec.read().to_vec();

        Box::into_raw(Box::new(Application::new(k.try_into().unwrap(), args)))
    }
}