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
//! 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::{IoError, IoReadError, IoWriteError},
    proc::{Application, DynStackElem, DynamicState, FuncPtr, Procedure, pop_dyn_stack},
    records::{Record, RecordTypeDescriptor, SchemeCompatible, rtd},
    registry::{bridge, cps_bridge},
    runtime::{Runtime, RuntimeInner},
    symbols::Symbol,
    syntax::{Identifier, Syntax, parse::ParseSyntaxError},
    value::{UnpackedValue, Value},
    vectors::Vector,
};
use parking_lot::RwLock;
use scheme_rs_macros::runtime_fn;
use std::{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)]
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!(
                    "Invalid index of {index} into 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!(
                    "Invalid range of {range:?} into 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 to receive {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!("Could not 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!("Could not represent '{value}' in {type} 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 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)
    }
}

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())
            }
        }
    };
}

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 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 })
    },
    debug: |this, f| {
        write!(f, " form: {:?} subform: {:?}", this.form, this.subform)
    }
);

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],
    dyn_state: &mut DynamicState,
    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()?;

    dyn_state.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 = dyn_state.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],
    dyn_state: &mut DynamicState,
    _k: Value,
) -> Result<Application, Exception> {
    Ok(raise(runtime.clone(), args[0].clone(), dyn_state))
}

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

    Application::new(
        dyn_state.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 (),
    dyn_state: *mut DynamicState,
) -> *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,
            dyn_state.as_mut().unwrap_unchecked(),
        )))
    }
}

unsafe extern "C" fn unwind_to_exception_handler(
    runtime: *mut GcInner<RwLock<RuntimeInner>>,
    env: *const Value,
    _args: *const Value,
    dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        // env[0] is the raised value:
        let raised = env.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(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(dyn_state.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(dyn_state.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,
    _dyn_state: *mut DynamicState,
) -> *mut Application {
    unsafe {
        let runtime = Runtime(Gc::from_raw_inc_rc(runtime));

        // env[0] is the exception
        let exception = env.as_ref().unwrap().clone();

        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],
    dyn_state: &mut DynamicState,
    k: Value,
) -> Result<Application, Exception> {
    let [condition] = args else {
        unreachable!();
    };

    let Some(handler) = dyn_state.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,
    )))))
}