scheme-rs 0.2.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
//! Exceptional situations and conditions.
//!
//! Scheme has two distinct concepts: conditions and exceptions. Exceptions are
//! values that values passed to the `raise` and `raise-continuable` procedures
//! and can be any [`Value`]. Conditions are records that contain information
//! describing an erroneous situation or _condition_.
//!
//! Conditions in Scheme are either [simple](`SimpleCondition`) or
//! [compound](`CompoundCondition`). Scheme-rs provides the ability to inspect
//! conditions without discerning whether they or simple or compound. Using the
//! [`condition`](Exception::condition) method, a specific condition and thus
//! its associated information can be extracted from the condition.
//!
//! For example, a common condition is the [`&trace`](StackTrace) condition,
//! which can be used to extract a stack trace for the exception:
//!
//! ```
//! # use scheme_rs::{exceptions::{Exception, Message, SyntaxViolation, StackTrace}, gc::Gc, syntax::Syntax};
//! // Code from scheme-rs repl to print errors:
//! fn print_exception(exception: Exception) {
//!     let Ok(conditions) = exception.simple_conditions() else {
//!         println!(
//!             "Exception occurred with a non-condition value: {:?}",
//!             exception.0
//!         );
//!         return;
//!     };
//!     println!("Uncaught exception:");
//!     for condition in conditions.into_iter() {
//!         if let Some(message) = condition.cast_to_rust_type::<Message>() {
//!             println!(" - Message: {}", message.message);
//!         } else if let Some(syntax) = condition.cast_to_rust_type::<SyntaxViolation>() {
//!             println!(" - Syntax error in form: {:?}", syntax.form);
//!             if let Some(subform) = syntax.subform.as_ref() {
//!                 println!("   (subform: {subform:?})");
//!             }
//!         } else if let Some(trace) = condition.cast_to_rust_type::<StackTrace>() {
//!             println!(" - Stack trace:");
//!             for (i, trace) in trace.trace.iter().enumerate() {
//!                 let syntax = trace.cast_to_scheme_type::<Gc<Syntax>>().unwrap();
//!                 let span = syntax.span();
//!                 let func_name = syntax.as_ident().unwrap().symbol();
//!                 println!("{:>6}: {func_name}:{span}", i + 1);
//!             }
//!         } else {
//!             println!(" - Condition: {condition:?}");
//!         }
//!     }
//! }
//! ```

use crate::{
    gc::{Gc, GcInner, Trace},
    lists::slice_to_list,
    ports::{IoDecodingError, IoEncodingError, IoError, IoReadError, IoWriteError},
    proc::{Application, ContBarrier, DynStackElem, FuncPtr, Procedure, pop_dyn_stack},
    records::{Record, RecordTypeDescriptor, SchemeCompatible, rtd},
    registry::{bridge, cps_bridge},
    runtime::{Runtime, RuntimeInner},
    symbols::Symbol,
    syntax::{Identifier, Span, Syntax, parse::ParseSyntaxError},
    value::{UnpackedValue, Value},
    vectors::Vector,
};
use by_address::ByAddress;
use parking_lot::RwLock;
use scheme_rs_macros::runtime_fn;
use std::{collections::HashMap, convert::Infallible, fmt, ops::Range, sync::Arc};

/// A macro for easily creating new condition types.
pub use scheme_rs_macros::define_condition_type;

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

/// A signal of some sort of erroneous condition.
#[derive(Debug, Clone, Trace)]
pub struct Exception(pub Value);

impl Exception {
    pub fn error(message: impl fmt::Display) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((Assertion::new(), Message::new(message.to_string()))),
        )))
    }

    pub fn syntax(form: Syntax, subform: Option<Syntax>) -> Self {
        Self(Value::from(Record::from_rust_type(SyntaxViolation::new(
            form, subform,
        ))))
    }

    pub fn undefined(ident: Identifier) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Undefined::new(),
                Message::new(format!("undefined variable {}", ident.sym)),
            )),
        )))
    }

    pub fn type_error(expected: &str, provided: &str) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "expected value of type {expected}, provided {provided}"
                )),
            )),
        )))
    }

    pub fn invalid_operator(provided: &str) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "invalid operator: expected procedure, provided {provided}"
                )),
            )),
        )))
    }

    pub fn invalid_index(index: usize, len: usize) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "index {index} out of bounds for collection of size {len}"
                )),
            )),
        )))
    }

    pub fn invalid_range(range: Range<usize>, len: usize) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "range {range:?} out of bounds for collection of size {len}"
                )),
            )),
        )))
    }

    pub fn wrong_num_of_unicode_chars(expected: usize, provided: usize) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "expected {expected} unicode characters from transform, received {provided}"
                )),
            )),
        )))
    }

    pub fn wrong_num_of_args(expected: usize, provided: usize) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "expected {expected} arguments, provided {provided}"
                )),
            )),
        )))
    }

    pub fn wrong_num_of_var_args(expected: Range<usize>, provided: usize) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!(
                    "expected {} to {} arguments, provided {provided}",
                    expected.start, expected.end
                )),
            )),
        )))
    }

    pub fn implementation_restriction(msg: impl fmt::Display) -> Self {
        Self(Value::from_rust_type(CompoundCondition::from((
            Assertion::new(),
            ImplementationRestriction::new(),
            Message::new(msg),
        ))))
    }

    /// For when we cannot convert a value into the requested type.
    ///
    /// Example: Integer to a Complex
    pub fn conversion_error(expected: &str, provided: &str) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!("cannot convert {provided} into {expected}")),
            )),
        )))
    }

    /// For when we cannot represent the value into the requested type.
    ///
    /// Example: an u128 number as an u8
    pub fn not_representable(value: &str, r#type: &str) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                Assertion::new(),
                Message::new(format!("cannot represent '{value}' as {type}")),
            )),
        )))
    }

    pub fn io_error(message: impl fmt::Display) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((IoError::new(), Assertion::new(), Message::new(message))),
        )))
    }

    pub fn io_read_error(message: impl fmt::Display) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((IoReadError::new(), Assertion::new(), Message::new(message))),
        )))
    }

    pub fn io_write_error(message: impl fmt::Display) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((IoWriteError::new(), Assertion::new(), Message::new(message))),
        )))
    }

    pub fn io_decoding_error(message: impl fmt::Display, port: Value) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                IoDecodingError::new(port),
                Assertion::new(),
                Message::new(message),
            )),
        )))
    }

    pub fn io_encoding_error(message: impl fmt::Display, port: Value, chr: char) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from((
                IoEncodingError::new(port, chr),
                Assertion::new(),
                Message::new(message),
            )),
        )))
    }

    pub fn invalid_record_index(k: usize) -> Self {
        Self::error(format!("invalid record index: {k}"))
    }

    pub fn add_condition(self, condition: impl SchemeCompatible) -> Self {
        let mut conditions = if let Some(compound) = self.0.cast_to_rust_type::<CompoundCondition>()
        {
            compound.0.clone()
        } else {
            vec![self.0]
        };

        conditions.push(Value::from(Record::from_rust_type(condition)));

        Self(Value::from(Record::from_rust_type(CompoundCondition(
            conditions,
        ))))
    }

    pub fn simple_conditions(&self) -> Result<Vec<Value>, Exception> {
        if self.0.cast_to_rust_type::<SimpleCondition>().is_some() {
            Ok(vec![self.0.clone()])
        } else if let Some(compound_condition) = self.0.cast_to_rust_type::<CompoundCondition>() {
            Ok(compound_condition.0.clone())
        } else {
            Err(Exception::error("not a simple or compound condition"))
        }
    }

    pub fn condition<T: SchemeCompatible>(&self) -> Result<Option<Gc<T>>, Exception> {
        for condition in self.simple_conditions()?.into_iter() {
            if let Some(condition) = condition.cast_to_rust_type::<T>() {
                return Ok(Some(condition));
            }
        }
        Ok(None)
    }

    pub fn pretty_print(
        &self,
        source_cache: &mut SourceCache,
        f: &mut impl fmt::Write,
    ) -> fmt::Result {
        let Ok(conditions) = self.simple_conditions() else {
            return writeln!(
                f,
                "Exception occurred with a non-condition value: {:?}",
                self.0
            );
        };

        writeln!(f, "Uncaught exception:")?;
        for condition in conditions.into_iter().rev() {
            if let Some(message) = condition.cast_to_rust_type::<Message>() {
                writeln!(f, " - Message: {}", message.message)?;
            } else if let Some(syntax) = condition.cast_to_rust_type::<SyntaxViolation>() {
                writeln!(f, " - Syntax error in form: {:?}", syntax.form)?;
                source_cache.pretty_print_condition(syntax.as_ref(), f)?;
            } else if let Some(trace) = condition.cast_to_rust_type::<StackTrace>() {
                if !trace.trace.is_empty() {
                    writeln!(f, " - Trace:")?;
                    source_cache.pretty_print_condition(trace.as_ref(), f)?;
                }
            } else if condition.cast_to_rust_type::<Assertion>().is_some() {
                writeln!(f, " - Assertion failed")?;
            } else {
                writeln!(f, " - Condition: {condition:?}")?;
            }
        }
        Ok(())
    }
}

impl From<&'_ Value> for Option<Exception> {
    fn from(value: &'_ Value) -> Self {
        if let UnpackedValue::Record(record) = &*value.unpacked_ref()
            && let rtd = record.rtd()
            && (RecordTypeDescriptor::is_subtype_of(&rtd, &SimpleCondition::rtd())
                || RecordTypeDescriptor::is_subtype_of(&rtd, &CompoundCondition::rtd()))
        {
            Some(Exception(value.clone()))
        } else {
            None
        }
    }
}

impl From<std::io::Error> for Exception {
    fn from(value: std::io::Error) -> Self {
        Self::from((IoError::new(), Message::new(format!("{value:?}"))))
    }
}

impl From<SimpleCondition> for Exception {
    fn from(simple: SimpleCondition) -> Self {
        Self(Value::from(Record::from_rust_type(simple)))
    }
}

impl From<Warning> for Exception {
    fn from(warning: Warning) -> Self {
        Self(Value::from(Record::from_rust_type(warning)))
    }
}

impl From<Serious> for Exception {
    fn from(serious: Serious) -> Self {
        Self(Value::from(Record::from_rust_type(serious)))
    }
}

impl From<Message> for Exception {
    fn from(message: Message) -> Self {
        Self(Value::from(Record::from_rust_type(message)))
    }
}

impl From<Infallible> for Exception {
    fn from(infallible: Infallible) -> Self {
        match infallible {}
    }
}

impl From<ParseSyntaxError> for Exception {
    fn from(error: ParseSyntaxError) -> Self {
        Self::from((Lexical::new(), Message::new(error)))
    }
}

macro_rules! impl_into_condition_for {
    ($for:ty) => {
        impl From<$for> for Exception {
            fn from(e: $for) -> Self {
                Self::error(e.to_string())
            }
        }
    };
}

pub trait PrettyCondition {
    fn span(&self) -> Span;

    fn pretty_print(&self, _w: &mut impl fmt::Write) -> fmt::Result {
        Ok(())
    }
}

/// Pretty print a condition with source information, heavily inspired by
/// [T8Err::render](https://github.com/xnacly/tango8/blob/master/shared/src/err.rs#L11)
fn print_lines_with_offense_from_span(
    span: &Span,
    lines: Option<&[String]>,
    w: &mut impl fmt::Write,
) -> fmt::Result {
    let Some(lines) = lines else {
        return Ok(());
    };

    writeln!(w, "--> {}:{}:{}:", span.file, span.line, span.column)?;
    let start = span.line.saturating_sub(2);
    let end = (span.line + 3).min(lines.len() as u32);

    for i in start..end {
        //  <line num> | <line content>
        //  +1, because 0 addressing
        writeln!(w, "{:03} | {}", i + 1, lines[i as usize])?;
        //  +1, because span.line is somehow not 0 addressed :O
        if i + 1 == span.line {
            writeln!(w, "    | {}~ here", " ".repeat(span.column))?; //  | <spacing until column>~
        }
    }
    Ok(())
}

impl_into_condition_for!(std::num::TryFromIntError);

#[derive(Copy, Clone, Default, Trace)]
pub struct SimpleCondition;

impl SimpleCondition {
    pub fn new() -> Self {
        Self
    }
}

impl SchemeCompatible for SimpleCondition {
    fn rtd() -> Arc<RecordTypeDescriptor> {
        rtd!(
            lib: "(rnrs conditions (6))",
            name: "&condition",
            constructor: || Ok(SimpleCondition)
        )
    }
}

impl fmt::Debug for SimpleCondition {
    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}

#[bridge(name = "condition?", lib = "(rnrs conditions (6))")]
pub fn condition_pred(obj: &Value) -> Result<Vec<Value>, Exception> {
    let is_condition = obj.cast_to_rust_type::<SimpleCondition>().is_some()
        || obj.cast_to_rust_type::<CompoundCondition>().is_some();
    Ok(vec![Value::from(is_condition)])
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Message,
    scheme_name: "&message",
    parent: SimpleCondition,
    fields: {
        message: String,
    },
    constructor: |message| {
        Ok(Message { parent: Gc::new(SimpleCondition::new()), message: message.to_string() })
    },
    debug: |this, f| {
        write!(f, " ")?;
        this.message.fmt(f)
    }
);

impl Message {
    pub fn new(message: impl fmt::Display) -> Self {
        Self {
            parent: Gc::new(SimpleCondition::new()),
            message: message.to_string(),
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Warning,
    scheme_name: "&warning",
    parent: SimpleCondition,
);

impl Warning {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(SimpleCondition::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Serious,
    scheme_name: "&serious",
    parent: SimpleCondition,
);

impl Serious {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(SimpleCondition::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: StackTrace,
    scheme_name: "&trace",
    parent: SimpleCondition,
    fields: {
        trace: Vector,
    },
    constructor: |trace| {
        Ok(StackTrace {
            parent: Gc::new(SimpleCondition::new()),
            trace: trace.clone().try_into()?,
        })
    },
    debug: |this, f| {
        for trace in &*this.trace.0.vec.read() {
            write!(f, " {trace}")?;
        }
        Ok(())
    }
);

impl PrettyCondition for StackTrace {
    fn span(&self) -> Span {
        let first = self.trace.first().unwrap();
        let Some(syntax) = first.cast_to_scheme_type::<Gc<Syntax>>() else {
            return Span::default();
        };
        syntax.span().clone()
    }

    fn pretty_print(&self, w: &mut impl fmt::Write) -> fmt::Result {
        for (i, trace) in self.trace.iter().enumerate() {
            let Some(syntax) = trace.cast_to_scheme_type::<Gc<Syntax>>() else {
                continue;
            };
            let span = syntax.span();
            let func_name = syntax.as_ident().unwrap().symbol();
            writeln!(w, "{:>6}: {func_name}:{span}", i + 1)?;
        }
        Ok(())
    }
}

impl StackTrace {
    pub fn new(trace: Vec<Value>) -> Self {
        Self {
            parent: Gc::new(SimpleCondition::new()),
            trace: Vector::from(trace),
        }
    }

    pub fn trace(&self) -> Vec<Syntax> {
        todo!()
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Error,
    scheme_name: "&error",
    parent: Serious,
);

impl Error {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(Serious::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: ImportError,
    scheme_name: "&import",
    parent: Error,
    fields: {
        library: String,
    },
    constructor: |lib| {
        Ok(ImportError {  parent: Gc::new(Error::new()), library: lib.to_string() })
    },
    debug: |this, f| {
        write!(f, " library: {}", this.library)
    }
);

impl ImportError {
    pub fn new(library: String) -> Self {
        Self {
            parent: Gc::new(Error::new()),
            library,
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Violation,
    scheme_name: "&violation",
    parent: Serious,
);

impl Violation {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(Serious::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Assertion,
    scheme_name: "&assertion",
    parent: Violation
);

impl Assertion {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(Violation::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Irritants,
    scheme_name: "&irritants",
    parent: SimpleCondition,
    fields: {
        irritants: Value,
    },
    constructor: |irritants| {
        Ok(Irritants { parent: Gc::new(SimpleCondition::new()), irritants })
    },
    debug: |this, f| {
        write!(f, " irritants: {:?}", this.irritants)
    }
);

impl Irritants {
    pub fn new(irritants: Value) -> Self {
        Irritants {
            parent: Gc::new(SimpleCondition::new()),
            irritants,
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Who,
    scheme_name: "&who",
    parent: SimpleCondition,
    fields: {
        who: Value,
    },
    constructor: |who| {
        Ok(Who { parent: Gc::new(SimpleCondition::new()), who, })
    },
    debug: |this, f| {
        write!(f, " who: {:?}", this.who)
    }
);

impl Who {
    pub fn new(who: Value) -> Self {
        Who {
            parent: Gc::new(SimpleCondition::new()),
            who,
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: NonContinuable,
    scheme_name: "&non-continuable",
    parent: Violation,
);

impl Default for NonContinuable {
    fn default() -> Self {
        Self {
            parent: Gc::new(Violation::new()),
        }
    }
}
define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: ImplementationRestriction,
    scheme_name: "&implementation-restriction",
    parent: Violation,
);

impl ImplementationRestriction {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for ImplementationRestriction {
    fn default() -> Self {
        Self {
            parent: Gc::new(Violation::new()),
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Lexical,
    scheme_name: "&lexical",
    parent: Violation,
);

impl Lexical {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(Violation::new()),
        }
    }
}

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

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: SyntaxViolation,
    scheme_name: "&syntax",
    parent: Violation,
    fields: {
        form: Value,
        subform: Option<Value>,
    },
    constructor: |form, subform| {
        let subform = if subform.is_true() { Some(subform) } else { None };
        Ok(SyntaxViolation { parent: Gc::new(Violation::new()), form, subform })
    },
);

impl PrettyCondition for SyntaxViolation {
    fn span(&self) -> Span {
        self.subform
            .as_ref()
            .unwrap_or(&self.form)
            .cast_to_scheme_type::<Gc<Syntax>>()
            .unwrap()
            .span()
            .clone()
    }
}

impl SyntaxViolation {
    pub fn new(form: Syntax, subform: Option<Syntax>) -> Self {
        Self {
            parent: Gc::new(Violation::new()),
            form: Value::from(form),
            subform: subform.map(Value::from),
        }
    }

    pub fn new_from_values(form: Value, subform: Option<Value>) -> Self {
        Self {
            parent: Gc::new(Violation::new()),
            form,
            subform,
        }
    }
}

define_condition_type!(
    lib: "(rnrs conditions (6))",
    rust_name: Undefined,
    scheme_name: "&undefined",
    parent: Violation
);

impl Undefined {
    pub fn new() -> Self {
        Self {
            parent: Gc::new(Violation::new()),
        }
    }
}

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

#[derive(Clone, Trace)]
pub struct CompoundCondition(pub(crate) Vec<Value>);

impl SchemeCompatible for CompoundCondition {
    fn rtd() -> Arc<RecordTypeDescriptor> {
        rtd!(
            lib: "(rnrs conditions (6))",
            name: "compound-condition",
            sealed: true,
            opaque: true
        )
    }
}

impl fmt::Debug for CompoundCondition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for cond in self.0.iter() {
            write!(f, " ")?;
            cond.fmt(f)?;
        }
        Ok(())
    }
}

impl<T> From<T> for Exception
where
    CompoundCondition: From<T>,
{
    fn from(value: T) -> Self {
        Self(Value::from(Record::from_rust_type(
            CompoundCondition::from(value),
        )))
    }
}

impl<A, B> From<(A, B)> for CompoundCondition
where
    A: SchemeCompatible,
    B: SchemeCompatible,
{
    fn from(value: (A, B)) -> Self {
        Self(vec![
            Value::from(Record::from_rust_type(value.0)),
            Value::from(Record::from_rust_type(value.1)),
        ])
    }
}

impl<A, B, C> From<(A, B, C)> for CompoundCondition
where
    A: SchemeCompatible,
    B: SchemeCompatible,
    C: SchemeCompatible,
{
    fn from(value: (A, B, C)) -> Self {
        Self(vec![
            Value::from(Record::from_rust_type(value.0)),
            Value::from(Record::from_rust_type(value.1)),
            Value::from(Record::from_rust_type(value.2)),
        ])
    }
}

#[bridge(name = "condition", lib = "(rnrs conditions (6))")]
pub fn condition(conditions: &[Value]) -> Result<Vec<Value>, Exception> {
    match conditions {
        // TODO: Check if this is a condition
        [simple_condition] => Ok(vec![simple_condition.clone()]),
        conditions => Ok(vec![Value::from(Record::from_rust_type(
            CompoundCondition(conditions.to_vec()),
        ))]),
    }
}

#[bridge(name = "simple-conditions", lib = "(rnrs conditions (6))")]
pub fn simple_conditions(condition: &Value) -> Result<Vec<Value>, Exception> {
    Ok(vec![slice_to_list(
        &Exception(condition.clone()).simple_conditions()?,
    )])
}

#[doc(hidden)]
#[cps_bridge(
    def = "with-exception-handler handler thunk",
    lib = "(rnrs exceptions (6))"
)]
pub fn with_exception_handler(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    barrier: &mut ContBarrier,
    k: Value,
) -> Result<Application, Exception> {
    let [handler, thunk] = args else {
        unreachable!();
    };

    let handler: Procedure = handler.clone().try_into()?;
    let thunk: Procedure = thunk.clone().try_into()?;

    barrier.push_dyn_stack(DynStackElem::ExceptionHandler(handler));

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

    let k = barrier.new_k(
        runtime.clone(),
        vec![k.clone()],
        pop_dyn_stack,
        req_args,
        var,
    );

    Ok(Application::new(thunk, vec![Value::from(k)]))
}

#[doc(hidden)]
#[cps_bridge(def = "raise obj", lib = "(rnrs exceptions (6))")]
pub fn raise_builtin(
    runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    barrier: &mut ContBarrier,
    _k: Value,
) -> Result<Application, Exception> {
    Ok(raise(runtime.clone(), args[0].clone(), barrier))
}

/// Raises a non-continuable exception to the current exception handler.
pub fn raise(runtime: Runtime, raised: Value, barrier: &mut ContBarrier) -> Application {
    let raised = if let Some(condition) = raised.cast_to_scheme_type::<Exception>() {
        let trace = barrier.current_marks(Symbol::intern("trace"));
        Value::from(condition.add_condition(StackTrace::new(trace)))
    } else {
        raised
    };

    Application::new(
        barrier.new_k(runtime, vec![raised], unwind_to_exception_handler, 0, false),
        Vec::new(),
    )
}

#[runtime_fn]
unsafe extern "C" fn raise_rt(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    raised: *const (),
    barrier: *mut ContBarrier,
) -> *mut Application {
    unsafe {
        let runtime = Runtime::from_raw_inc_rc(runtime);
        let raised = Value::from_raw(raised);
        Box::into_raw(Box::new(raise(
            runtime,
            raised,
            barrier.as_mut().unwrap_unchecked(),
        )))
    }
}

unsafe extern "C" fn unwind_to_exception_handler(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    barrier: *mut ContBarrier,
) -> *mut Application {
    unsafe {
        // env[0] is the raised value:
        let raised = env.as_ref().unwrap().clone();

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

        loop {
            let app = match barrier.pop_dyn_stack() {
                None => {
                    // If the stack is empty, we should return the error
                    Application::halt_err(raised)
                }
                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(barrier.new_k(
                            Runtime::from_raw_inc_rc(runtime),
                            vec![raised],
                            unwind_to_exception_handler,
                            0,
                            false,
                        ))],
                    )
                }
                Some(DynStackElem::ExceptionHandler(handler)) => Application::new(
                    handler,
                    vec![
                        raised.clone(),
                        Value::from(barrier.new_k(
                            Runtime::from_raw_inc_rc(runtime),
                            vec![raised],
                            reraise_exception,
                            0,
                            true,
                        )),
                    ],
                ),
                _ => continue,
            };
            return Box::into_raw(Box::new(app));
        }
    }
}

unsafe extern "C" fn reraise_exception(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    _env: *const Value,
    _args: *const Value,
    _barrier: *mut ContBarrier,
) -> *mut Application {
    unsafe {
        let runtime = Runtime(Gc::from_raw_inc_rc(runtime));

        /*
        // env[0] is the exception
        let exception = env.as_ref().unwrap().clone();
         */
        let exception = Value::from_rust_type(NonContinuable::default());

        Box::into_raw(Box::new(Application::new(
            Procedure::new(
                runtime,
                Vec::new(),
                FuncPtr::Bridge(raise_builtin),
                1,
                false,
            ),
            vec![exception, Value::undefined()],
        )))
    }
}

/// Raises an exception to the current exception handler and continues with the
/// value returned by the handler.
#[doc(hidden)]
#[cps_bridge(def = "raise-continuable obj", lib = "(rnrs exceptions (6))")]
pub fn raise_continuable(
    _runtime: &Runtime,
    _env: &[Value],
    args: &[Value],
    _rest_args: &[Value],
    barrier: &mut ContBarrier,
    k: Value,
) -> Result<Application, Exception> {
    let [condition] = args else {
        unreachable!();
    };

    let Some(handler) = barrier.current_exception_handler() else {
        return Ok(Application::halt_err(condition.clone()));
    };

    Ok(Application::new(handler, vec![condition.clone(), k]))
}

#[bridge(name = "error", lib = "(rnrs base builtins (6))")]
pub fn error(who: &Value, message: &Value, irritants: &[Value]) -> Result<Vec<Value>, Exception> {
    let mut conditions = Vec::new();
    if who.is_true() {
        conditions.push(Value::from_rust_type(Who::new(who.clone())));
    }
    conditions.push(Value::from_rust_type(Message::new(message)));
    conditions.push(Value::from_rust_type(Irritants::new(slice_to_list(
        irritants,
    ))));
    Err(Exception(Value::from(Exception::from(CompoundCondition(
        conditions,
    )))))
}

#[bridge(name = "assertion-violation", lib = "(rnrs base builtins (6))")]
pub fn assertion_violation(
    who: &Value,
    message: &Value,
    irritants: &[Value],
) -> Result<Vec<Value>, Exception> {
    let mut conditions = Vec::new();
    conditions.push(Value::from_rust_type(Assertion::new()));
    if who.is_true() {
        conditions.push(Value::from_rust_type(Who::new(who.clone())));
    }
    conditions.push(Value::from_rust_type(Message::new(message)));
    conditions.push(Value::from_rust_type(Irritants::new(slice_to_list(
        irritants,
    ))));
    Err(Exception(Value::from(Exception::from(CompoundCondition(
        conditions,
    )))))
}

/// Store of source files for pretty printing error messages.
#[derive(Default, Trace)]
pub struct SourceCache {
    cache: HashMap<ByAddress<Arc<str>>, Vec<String>>,
}

impl SourceCache {
    pub fn store(&mut self, file_name: Arc<str>, lines: Vec<String>) {
        self.cache.insert(ByAddress(file_name), lines);
    }

    // #[maybe_await]
    pub fn fetch(&mut self, file_name: &Arc<str>) -> Option<&[String]> {
        if !self.cache.contains_key(ByAddress::from_ref(file_name)) {
            let lines = std::fs::read_to_string(file_name.as_ref())
                .ok()?
                .lines()
                .map(|x| x.to_string())
                .collect::<Vec<_>>();
            self.cache.insert(ByAddress(file_name.clone()), lines);
        }
        self.cache
            .get(ByAddress::from_ref(file_name))
            .map(|lines| lines.as_ref())
    }

    pub fn pretty_print_condition(
        &mut self,
        pe: &impl PrettyCondition,
        w: &mut impl fmt::Write,
    ) -> fmt::Result {
        let span = pe.span();
        let lines = self.fetch(&span.file);
        pe.pretty_print(w)?;
        print_lines_with_offense_from_span(&span, lines, w)
    }
}