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
//! We expose the Wren API in a Rust-y way
pub extern crate wren_sys;

use foreign_v2::ForeignItem;
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::{Rc, Weak};
use std::sync::mpsc::{channel, Receiver, Sender};
use wren_sys::{wrenGetUserData, WrenConfiguration, WrenHandle, WrenVM};

mod module_loader;
pub use module_loader::{BasicFileLoader, NullLoader};

pub mod foreign_v1;
pub mod foreign_v2;

use std::{any, ffi, marker, mem, os::raw};

mod runtime;
#[cfg(test)]
mod tests;
#[cfg(feature = "derive")]
pub use ruwren_macros::*;

#[derive(Debug)]
/// Directly internally to report errors
pub enum WrenError {
    Compile(String, i32, String),
    Runtime(String),
    StackTrace(String, i32, String),
}

#[derive(Debug, Clone)]
/// Possible errors for a Wren script
pub enum VMError {
    Compile {
        module: String,
        line: i32,
        error: String,
    },
    Runtime {
        error: String,
        frames: Vec<VMStackFrameError>,
    },
}

#[derive(Debug, Clone)]
pub struct VMStackFrameError {
    pub module: String,
    pub line: i32,
    pub function: String,
}

#[cfg(not(target_arch = "wasm32"))]
pub fn handle_panic<F, O>(func: F) -> Result<O, Box<dyn Any + Send>>
where
    F: FnOnce() -> O + std::panic::UnwindSafe,
{
    std::panic::catch_unwind(func)
}

#[cfg(target_arch = "wasm32")]
pub fn handle_panic<F, O: 'static>(func: F) -> Result<O, Box<dyn Any + Send>>
where
    F: FnOnce() -> O + std::panic::UnwindSafe,
{
    match std::panic::catch_unwind(func) {
        Ok(o) => Ok(o),
        _ => unreachable!("non-unwinding platforms (like WASM) can't catch unwinds, so don't panic unless absolutely necessary"),
    }
}

impl std::fmt::Display for VMError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            VMError::Compile {
                module,
                line,
                error,
            } => write!(fmt, "Compile Error ({}:{}): {}", module, line, error),
            VMError::Runtime { error, frames } => {
                writeln!(fmt, "Runtime Error: {}", error)?;
                for frame in frames {
                    if frame.function.is_empty() {
                        writeln!(fmt, "\tin {}:{}: <constructor>", frame.module, frame.line)?;
                    } else {
                        writeln!(
                            fmt,
                            "\tin {}:{}: {}",
                            frame.module, frame.line, frame.function
                        )?;
                    }
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for VMError {}

/// A handle to a Wren object
#[derive(Debug, PartialEq, Eq)]
pub struct Handle<'a> {
    handle: *mut WrenHandle,
    wvm: *mut WrenVM,
    vm: marker::PhantomData<&'a VM>,
}

impl<'a> Drop for Handle<'a> {
    fn drop(&mut self) {
        unsafe {
            wren_sys::wrenReleaseHandle(self.wvm, self.handle);
        }
    }
}

/// A handle to a Wren method call
#[derive(Debug, PartialEq, Eq)]
pub struct FunctionHandle<'a>(Handle<'a>);

/// Simulates a module structure for foreign functions
#[derive(Debug, Clone, Default)]
pub struct ModuleLibrary {
    modules: HashMap<String, Module>,
}

impl ModuleLibrary {
    /// Creates a new library
    pub fn new() -> ModuleLibrary {
        ModuleLibrary {
            modules: HashMap::new(),
        }
    }

    /// Adds a [`Module`] with a specified `name`
    pub fn module<N: Into<String>>(&mut self, name: N, modl: Module) {
        let module_name = name.into();
        if let Some(module) = self.modules.get_mut(&module_name) {
            module.classes.extend(modl.classes);
        } else {
            self.modules.insert(module_name, modl);
        }
    }

    /// Attempts to find a [`RuntimeClass`] given a `module` name and a `class` name
    fn get_foreign_class<M: AsRef<str>, C: AsRef<str>>(
        &self, module: M, class: C,
    ) -> Option<&RuntimeClass> {
        self.modules
            .get(module.as_ref())
            .and_then(|md| md.classes.get(class.as_ref()))
    }
}

#[derive(Debug, Clone)]
/// Represetnation of classes at runtime
struct RuntimeClass {
    construct: extern "C" fn(*mut WrenVM),
    destruct: extern "C" fn(*mut ffi::c_void),
    methods: ClassObjectPointers,

    // Use for "loading in" appropriate objects
    type_id: any::TypeId,
}

#[derive(Debug, Clone, Default)]
/// A container for `RuntimeClass` structs
pub struct Module {
    classes: HashMap<String, RuntimeClass>,
}

#[derive(Debug, Clone)]
/// List of [`MethodPointer`]s that make up the methods of a ['RuntimeClass`]
pub struct ClassObjectPointers {
    pub function_pointers: Vec<MethodPointer>,
}

#[derive(Debug, Clone)]
pub struct MethodPointer {
    pub is_static: bool,
    pub signature: FunctionSignature,
    pub pointer: unsafe extern "C" fn(*mut WrenVM),
}

impl Module {
    /// Create a new module
    pub fn new() -> Module {
        Module {
            classes: HashMap::new(),
        }
    }

    /// Add class `C` to this module with a `name`
    pub fn class<C: 'static + ClassObject, S: Into<String>>(&mut self, name: S) -> &mut Self {
        let cp = C::generate_pointers();
        let init = C::initialize_pointer();
        let deinit = C::finalize_pointer();
        self.classes.insert(
            name.into(),
            RuntimeClass {
                construct: init,
                destruct: deinit,
                methods: cp,
                type_id: any::TypeId::of::<C>(),
            },
        );
        self
    }
}

/// Initialize function for Wren classes
pub trait Class {
    fn initialize(_: &VM) -> Self
    where
        Self: Sized;
}

/// Indicates a "real" Wren class, and must be implemented to be added to a [`Module`]
pub trait ClassObject: Class {
    fn initialize_pointer() -> extern "C" fn(*mut WrenVM)
    where
        Self: Sized;
    fn finalize_pointer() -> extern "C" fn(*mut ffi::c_void)
    where
        Self: Sized;
    fn generate_pointers() -> ClassObjectPointers
    where
        Self: Sized;
}

#[derive(Debug, Copy, Clone)]
/// Indicates a "foreign object" to Wren
pub struct ForeignObject<T> {
    pub object: *mut T,
    pub type_id: any::TypeId,
}

pub fn type_name_of<T>(_: &T) -> &'static str {
    any::type_name::<T>()
}

/// Enables one to enable module loading for Wren
pub trait ModuleScriptLoader {
    /// Takes a desired module `name`
    ///
    /// ### Returns
    /// - `Some(String)` containing the Wren source if the module exists
    /// - `None` if not
    fn load_script(&mut self, name: String) -> Option<String>;
}

impl<T> ModuleScriptLoader for T
where
    T: FnMut(String) -> Option<String>,
{
    fn load_script(&mut self, name: String) -> Option<String> {
        (*self)(name)
    }
}

type Evm = Rc<RefCell<VM>>;

/// Sends strings for printing to an output
pub trait Printer {
    /// Called whenever a string is to be sent to output
    fn print(&mut self, s: String);
}

impl<T> Printer for T
where
    T: FnMut(String),
{
    fn print(&mut self, s: String) {
        (*self)(s)
    }
}

struct PrintlnPrinter;
impl Printer for PrintlnPrinter {
    fn print(&mut self, s: String) {
        print!("{}", s);
    }
}

type ClassMap = RefCell<HashMap<TypeId, Rc<RefCell<Box<dyn Any>>>>>;

#[derive(Debug)]
pub struct VM {
    pub vm: *mut WrenVM,
    classes_v2: ClassMap,
    error_recv: Receiver<WrenError>,
}

/// A mostly internal class that is exposed so that some externally generated code can access it.
pub struct UserData {
    error_channel: Sender<WrenError>,
    printer: Box<dyn Printer>,
    pub vm: Weak<RefCell<VM>>, // is used a *lot* by externally generated code.
    library: Option<ModuleLibrary>,
    loader: Box<dyn ModuleScriptLoader>,
}

/// Represents Wren slot types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotType {
    Num,
    Bool,
    List,
    Map,
    Null,
    String,
    Foreign,
    Unknown,
}

pub type SlotId = usize;

/// Represents Wren function signatures
#[derive(Debug, Clone)]
pub enum FunctionSignature {
    Function { name: String, arity: usize },
    Getter(String),
    Setter(String),
}

impl FunctionSignature {
    pub fn new_function<N: Into<String>>(name: N, arity: usize) -> FunctionSignature {
        FunctionSignature::Function {
            name: name.into(),
            arity,
        }
    }

    pub fn new_getter<N: Into<String>>(name: N) -> FunctionSignature {
        FunctionSignature::Getter(name.into())
    }

    pub fn new_setter<N: Into<String>>(name: N) -> FunctionSignature {
        FunctionSignature::Setter(name.into())
    }

    fn as_wren_string(&self) -> String {
        match self {
            FunctionSignature::Function { name, arity } => {
                format!("{}({})", name, vec!["_".to_string(); *arity].join(","))
            }
            FunctionSignature::Getter(name) => name.clone(),
            FunctionSignature::Setter(name) => format!("{}=(_)", name),
        }
    }

    /// Get number of arguments this function signature would require
    pub fn arity(&self) -> usize {
        match self {
            FunctionSignature::Function { arity, .. } => *arity,
            FunctionSignature::Getter(_) => 0,
            FunctionSignature::Setter(_) => 1,
        }
    }
}

/// High-level wrapper around a Wren VM
#[derive(Debug, Clone)]
pub struct VMWrapper(Evm);

impl VMWrapper {
    /// Calls a given function from its signature
    pub fn call(&self, signature: FunctionSignature) -> Result<(), VMError> {
        let handle = self.make_call_handle(signature);
        self.call_handle(&handle)
    }

    /// Calls a given function from its handle
    pub fn call_handle(&self, handle: &FunctionHandle) -> Result<(), VMError> {
        let vm = self.0.borrow();
        match unsafe { wren_sys::wrenCall(vm.vm, handle.0.handle) } {
            wren_sys::WrenInterpretResult_WREN_RESULT_SUCCESS => Ok(()),
            wren_sys::WrenInterpretResult_WREN_RESULT_COMPILE_ERROR => {
                unreachable!("wrenCall doesn't compile anything")
            }
            wren_sys::WrenInterpretResult_WREN_RESULT_RUNTIME_ERROR => {
                let mut error = "".to_string();
                let mut frames = vec![];
                while let Ok(err) = vm.error_recv.try_recv() {
                    match err {
                        WrenError::Runtime(msg) => {
                            error = msg;
                        }
                        WrenError::StackTrace(module, line, msg) => {
                            frames.push(VMStackFrameError {
                                module,
                                line,
                                function: msg,
                            });
                        }
                        _ => unreachable!(),
                    }
                }
                Err(VMError::Runtime { error, frames })
            }
            _ => unreachable!(),
        }
    }

    /// Interprets a given string as Wren code
    pub fn interpret<M: AsRef<str>, C: AsRef<str>>(
        &self, module: M, code: C,
    ) -> Result<(), VMError> {
        let module = ffi::CString::new(module.as_ref()).expect("module name conversion failed");
        let code = ffi::CString::new(code.as_ref()).expect("code conversion failed");
        let vm = self.0.borrow();
        match unsafe { wren_sys::wrenInterpret(vm.vm, module.as_ptr(), code.as_ptr()) } {
            wren_sys::WrenInterpretResult_WREN_RESULT_SUCCESS => Ok(()),
            wren_sys::WrenInterpretResult_WREN_RESULT_COMPILE_ERROR => {
                match vm.error_recv.try_recv() {
                    Ok(WrenError::Compile(module, line, msg)) => Err(VMError::Compile {
                        module,
                        line,
                        error: msg,
                    }),
                    _ => unreachable!(),
                }
            }
            wren_sys::WrenInterpretResult_WREN_RESULT_RUNTIME_ERROR => {
                let mut error = "".to_string();
                let mut frames = vec![];
                while let Ok(err) = vm.error_recv.try_recv() {
                    match err {
                        WrenError::Runtime(msg) => {
                            error = msg;
                        }
                        WrenError::StackTrace(module, line, msg) => {
                            frames.push(VMStackFrameError {
                                module,
                                line,
                                function: msg,
                            });
                        }
                        _ => unreachable!(),
                    }
                }
                Err(VMError::Runtime { error, frames })
            }
            _ => unreachable!(),
        }
    }

    /// Allows access to the internal VM wrapper object
    pub fn execute<T, F>(&self, f: F) -> T
    where
        F: FnOnce(&VM) -> T,
    {
        f(&self.0.borrow())
    }

    /// Gets a handle to a value in a certain slot
    pub fn get_slot_handle(&self, slot: SlotId) -> Rc<Handle> {
        Rc::new(Handle {
            handle: unsafe { wren_sys::wrenGetSlotHandle(self.0.borrow().vm, slot as raw::c_int) },
            wvm: self.0.borrow().vm,
            vm: marker::PhantomData,
        })
    }

    /// Sets the value in a certain slot to the value of a handle
    pub fn set_slot_handle(&self, slot: SlotId, handle: &Handle) {
        unsafe {
            wren_sys::wrenSetSlotHandle(self.0.borrow().vm, slot as raw::c_int, handle.handle)
        }
    }

    /// Create a callable handle, that can be used with [`call_handle`](VMWrapper::call_handle)
    pub fn make_call_handle(&self, signature: FunctionSignature) -> Rc<FunctionHandle> {
        VM::make_call_handle(self.0.borrow().vm, signature)
    }

    /// Instruct Wren to start a garbage collection cycle
    pub fn collect_garbage(&self) {
        unsafe { wren_sys::wrenCollectGarbage(self.0.borrow().vm) }
    }
}

/// Allows for the customization of a Wren VM
pub struct VMConfig {
    printer: Box<dyn Printer>,
    script_loader: Box<dyn ModuleScriptLoader>,
    library: Option<ModuleLibrary>,
    initial_heap_size: usize,
    min_heap_size: usize,
    heap_growth_percent: usize,

    /// Enables @module syntax to mean `module` loaded relative to current module
    enable_relative_import: bool,
}

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

impl VMConfig {
    pub fn new() -> VMConfig {
        VMConfig {
            printer: Box::new(PrintlnPrinter),
            script_loader: Box::new(NullLoader),
            library: None,
            initial_heap_size: 1024 * 1024 * 10,
            min_heap_size: 1024 * 1024,
            heap_growth_percent: 50,
            enable_relative_import: false,
        }
    }

    pub fn printer<P: 'static + Printer>(mut self, p: P) -> Self {
        self.printer = Box::new(p);
        self
    }

    pub fn script_loader<L: 'static + ModuleScriptLoader>(mut self, l: L) -> Self {
        self.script_loader = Box::new(l);
        self
    }

    pub fn library(mut self, l: &ModuleLibrary) -> Self {
        self.library = Some(l.clone());
        self
    }

    pub fn no_library(mut self) -> Self {
        self.library = None;
        self
    }

    pub fn initial_heap_size(mut self, ihs: usize) -> Self {
        self.initial_heap_size = ihs;
        self
    }

    pub fn min_heap_size(mut self, mhs: usize) -> Self {
        self.min_heap_size = mhs;
        self
    }

    pub fn heap_growth_percent(mut self, hgp: usize) -> Self {
        self.heap_growth_percent = hgp;
        self
    }

    pub fn enable_relative_import(mut self, eri: bool) -> Self {
        self.enable_relative_import = eri;
        self
    }

    pub fn build(self) -> VMWrapper {
        let (etx, erx) = channel();

        // Have an uninitialized VM...
        let wvm = Rc::new(RefCell::new(VM {
            vm: std::ptr::null_mut(),
            classes_v2: RefCell::new(HashMap::new()),
            error_recv: erx,
        }));

        let vm_config = Box::into_raw(Box::new(UserData {
            error_channel: etx,
            printer: self.printer,
            vm: Rc::downgrade(&wvm),
            loader: self.script_loader,
            library: self.library,
        }));

        // Configure the Wren side of things
        let mut config = unsafe {
            let mut uconfig = mem::MaybeUninit::<WrenConfiguration>::zeroed();
            wren_sys::wrenInitConfiguration(uconfig.as_mut_ptr());
            let mut config = uconfig.assume_init();
            config.errorFn = Some(runtime::wren_error);
            config.writeFn = Some(runtime::wren_print);
            config.reallocateFn = Some(runtime::wren_realloc);
            config.bindForeignMethodFn = Some(runtime::wren_bind_foreign_method);
            config.bindForeignClassFn = Some(runtime::wren_bind_foreign_class);
            config.loadModuleFn = Some(runtime::wren_load_module);
            config.resolveModuleFn = if self.enable_relative_import {
                Some(runtime::wren_canonicalize)
            } else {
                None
            };
            config.initialHeapSize = self.initial_heap_size;
            config.minHeapSize = self.min_heap_size;
            config.heapGrowthPercent = self.heap_growth_percent as raw::c_int;
            config.userData = vm_config as *mut ffi::c_void;
            config
        };

        let vm = unsafe { wren_sys::wrenNewVM(&mut config) };
        wvm.borrow_mut().vm = vm;
        VMWrapper(wvm)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Errors that can happen when sending a foreign object to Wren
pub enum ForeignSendError {
    /// No ['RuntimeClass'] exists in the specfied module with the given name
    NoForeignClass,
    /// No Wrne declaration of the foreign class was made
    NoWrenClass,
    /// Ran out of memory to allocate the class
    NoMemory,
    /// The type of the ['RuntimeClass`] [`ClassObject`] differes from the given object
    ClassMismatch,
}

impl std::fmt::Display for ForeignSendError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ForeignSendError::NoForeignClass => write!(fmt, "no foreign class"),
            ForeignSendError::NoWrenClass => write!(fmt, "no Wren class"),
            ForeignSendError::NoMemory => write!(fmt, "unable to allocate memory"),
            ForeignSendError::ClassMismatch => write!(fmt, "class mismatch"),
        }
    }
}

impl std::error::Error for ForeignSendError {}

impl VM {
    // Slot and Handle API
    pub fn ensure_slots(&self, count: usize) {
        unsafe { wren_sys::wrenEnsureSlots(self.vm, count as raw::c_int) }
    }

    pub fn get_slot_count(&self) -> usize {
        unsafe { wren_sys::wrenGetSlotCount(self.vm) as usize }
    }

    pub fn set_slot_bool(&self, slot: SlotId, val: bool) {
        self.ensure_slots(slot + 1);
        unsafe { wren_sys::wrenSetSlotBool(self.vm, slot as raw::c_int, val) }
    }

    pub fn set_slot_double(&self, slot: SlotId, val: f64) {
        self.ensure_slots(slot + 1);
        unsafe { wren_sys::wrenSetSlotDouble(self.vm, slot as raw::c_int, val) }
    }

    pub fn set_slot_null(&self, slot: SlotId) {
        self.ensure_slots(slot + 1);
        unsafe { wren_sys::wrenSetSlotNull(self.vm, slot as raw::c_int) }
    }

    pub fn set_slot_bytes(&self, slot: SlotId, bytes: &[u8]) {
        self.ensure_slots(slot + 1);
        unsafe {
            wren_sys::wrenSetSlotBytes(
                self.vm,
                slot as raw::c_int,
                bytes as *const _ as *const raw::c_char,
                bytes.len(),
            );
        }
    }

    pub fn set_slot_string<S: AsRef<str>>(&self, slot: SlotId, string: S) {
        self.ensure_slots(slot + 1);
        let string = string.as_ref();
        unsafe {
            wren_sys::wrenSetSlotBytes(
                self.vm,
                slot as raw::c_int,
                string.as_ptr() as *const _,
                string.len(),
            );
        }
    }

    pub fn get_slot_bool(&self, slot: SlotId) -> Option<bool> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) != SlotType::Bool {
            None
        } else {
            unsafe { Some(wren_sys::wrenGetSlotBool(self.vm, slot as raw::c_int)) }
        }
    }

    pub fn get_slot_double(&self, slot: SlotId) -> Option<f64> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) != SlotType::Num {
            None
        } else {
            unsafe { Some(wren_sys::wrenGetSlotDouble(self.vm, slot as raw::c_int)) }
        }
    }

    pub fn get_slot_bytes(&self, slot: SlotId) -> Option<Vec<u8>> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) != SlotType::String {
            None
        } else {
            let mut length = 0 as raw::c_int;
            let ptr = unsafe {
                wren_sys::wrenGetSlotBytes(self.vm, slot as raw::c_int, &mut length as *mut _)
            };
            let mut bytes = vec![];

            // Do some pointer maths to get the vector. Hurrah!
            for offset in 0..length {
                unsafe { bytes.push(*ptr.offset(offset as isize) as u8) }
            }

            Some(bytes)
        }
    }

    pub fn get_slot_string(&self, slot: SlotId) -> Option<String> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) != SlotType::String {
            None
        } else {
            let ptr = unsafe { wren_sys::wrenGetSlotString(self.vm, slot as raw::c_int) };

            let cstr = unsafe { ffi::CStr::from_ptr(ptr) };

            Some(cstr.to_string_lossy().to_string())
        }
    }

    pub fn get_slot_type(&self, slot: SlotId) -> SlotType {
        self.ensure_slots(slot + 1);
        match unsafe { wren_sys::wrenGetSlotType(self.vm, slot as raw::c_int) } {
            wren_sys::WrenType_WREN_TYPE_NUM => SlotType::Num,
            wren_sys::WrenType_WREN_TYPE_BOOL => SlotType::Bool,
            wren_sys::WrenType_WREN_TYPE_LIST => SlotType::List,
            wren_sys::WrenType_WREN_TYPE_MAP => SlotType::Map,
            wren_sys::WrenType_WREN_TYPE_NULL => SlotType::Null,
            wren_sys::WrenType_WREN_TYPE_STRING => SlotType::String,
            wren_sys::WrenType_WREN_TYPE_FOREIGN => SlotType::Foreign,
            wren_sys::WrenType_WREN_TYPE_UNKNOWN => SlotType::Unknown,
            _ => unreachable!(),
        }
    }

    /// Returns Some(()) if the variable was found and stored in the given slot
    ///
    /// Returns None if the variable does not exist
    pub fn get_variable<M: AsRef<str>, N: AsRef<str>>(
        &self, module: M, name: N, slot: SlotId,
    ) -> bool {
        self.ensure_slots(slot + 1);
        if !self.has_variable(&module, &name) {
            return false;
        }
        let module = ffi::CString::new(module.as_ref()).expect("module name conversion failed");
        let name = ffi::CString::new(name.as_ref()).expect("variable name conversion failed");
        unsafe {
            wren_sys::wrenGetVariable(self.vm, module.as_ptr(), name.as_ptr(), slot as raw::c_int)
        }
        true
    }

    pub fn has_variable<M: AsRef<str>, N: AsRef<str>>(&self, module: M, name: N) -> bool {
        if !self.has_module(&module) {
            return false;
        }
        let module = ffi::CString::new(module.as_ref()).expect("module name conversion failed");
        let name = ffi::CString::new(name.as_ref()).expect("variable name conversion failed");
        unsafe { wren_sys::wrenHasVariable(self.vm, module.as_ptr(), name.as_ptr()) }
    }

    pub fn has_module<M: AsRef<str>>(&self, module: M) -> bool {
        let module = ffi::CString::new(module.as_ref()).expect("module name conversion failed");
        unsafe { wren_sys::wrenHasModule(self.vm, module.as_ptr()) }
    }

    pub fn set_slot_new_list(&self, slot: SlotId) {
        self.ensure_slots(slot + 1);
        unsafe { wren_sys::wrenSetSlotNewList(self.vm, slot as raw::c_int) }
    }

    pub fn get_list_count(&self, slot: SlotId) -> Option<usize> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) == SlotType::List {
            Some(unsafe { wren_sys::wrenGetListCount(self.vm, slot as raw::c_int) as usize })
        } else {
            None
        }
    }

    pub fn insert_in_list(&self, list_slot: SlotId, index: i32, element_slot: SlotId) {
        self.ensure_slots(element_slot + 1);
        self.ensure_slots(list_slot + 1);
        unsafe {
            wren_sys::wrenInsertInList(
                self.vm,
                list_slot as raw::c_int,
                index as raw::c_int,
                element_slot as raw::c_int,
            )
        }
    }

    pub fn get_list_element(&self, list_slot: SlotId, index: i32, element_slot: SlotId) {
        self.ensure_slots(element_slot + 1);
        self.ensure_slots(list_slot + 1);
        unsafe {
            wren_sys::wrenGetListElement(
                self.vm,
                list_slot as raw::c_int,
                index as raw::c_int,
                element_slot as raw::c_int,
            )
        }
    }

    pub fn set_list_element(&self, list_slot: SlotId, index: i32, element_slot: SlotId) {
        self.ensure_slots(element_slot + 1);
        self.ensure_slots(list_slot + 1);
        unsafe {
            wren_sys::wrenSetListElement(
                self.vm,
                list_slot as raw::c_int,
                index as raw::c_int,
                element_slot as raw::c_int,
            )
        }
    }

    pub fn set_slot_new_map(&self, slot: SlotId) {
        self.ensure_slots(slot + 1);
        unsafe { wren_sys::wrenSetSlotNewMap(self.vm, slot as raw::c_int) }
    }

    pub fn get_map_count(&self, slot: SlotId) -> Option<usize> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) == SlotType::Map {
            Some(unsafe { wren_sys::wrenGetMapCount(self.vm, slot as raw::c_int) as usize })
        } else {
            None
        }
    }

    pub fn get_map_contains_key(&self, map_slot: SlotId, key_slot: SlotId) -> Option<bool> {
        self.ensure_slots(map_slot + 1);
        self.ensure_slots(key_slot + 1);
        if self.get_slot_type(map_slot) == SlotType::Map {
            Some(unsafe {
                wren_sys::wrenGetMapContainsKey(
                    self.vm,
                    map_slot as raw::c_int,
                    key_slot as raw::c_int,
                )
            })
        } else {
            None
        }
    }

    pub fn get_map_value(&self, map_slot: SlotId, key_slot: SlotId, value_slot: SlotId) {
        self.ensure_slots(map_slot + 1);
        self.ensure_slots(key_slot + 1);
        self.ensure_slots(value_slot + 1);
        unsafe {
            wren_sys::wrenGetMapValue(
                self.vm,
                map_slot as raw::c_int,
                key_slot as raw::c_int,
                value_slot as raw::c_int,
            )
        }
    }

    pub fn set_map_value(&self, map_slot: SlotId, key_slot: SlotId, value_slot: SlotId) {
        self.ensure_slots(map_slot + 1);
        self.ensure_slots(key_slot + 1);
        self.ensure_slots(value_slot + 1);
        unsafe {
            wren_sys::wrenSetMapValue(
                self.vm,
                map_slot as raw::c_int,
                key_slot as raw::c_int,
                value_slot as raw::c_int,
            )
        }
    }

    pub fn remove_map_value(&self, map_slot: SlotId, key_slot: SlotId, removed_value_slot: SlotId) {
        self.ensure_slots(map_slot + 1);
        self.ensure_slots(key_slot + 1);
        self.ensure_slots(removed_value_slot + 1);
        unsafe {
            wren_sys::wrenRemoveMapValue(
                self.vm,
                map_slot as raw::c_int,
                key_slot as raw::c_int,
                removed_value_slot as raw::c_int,
            )
        }
    }

    pub fn get_slot_foreign<T: 'static + ClassObject>(&self, slot: SlotId) -> Option<&T> {
        self.ensure_slots(slot + 1);
        self.get_slot_foreign_mut(slot).map(|mr| &*mr)
    }

    pub fn get_slot_foreign_mut<T: 'static + ClassObject>(&self, slot: SlotId) -> Option<&mut T> {
        self.ensure_slots(slot + 1);
        if self.get_slot_type(slot) != SlotType::Foreign {
            return None;
        }
        unsafe {
            let ptr = wren_sys::wrenGetSlotForeign(self.vm, slot as raw::c_int);
            if !ptr.is_null() {
                let fo = std::ptr::read_unaligned(ptr as *mut ForeignObject<T>);
                let ret = if fo.type_id == any::TypeId::of::<T>() {
                    // Safe to downcast
                    fo.object.as_mut()
                } else {
                    // Incorrect type, unsafe to downcast
                    None
                };
                std::ptr::write_unaligned(ptr as *mut ForeignObject<T>, fo);
                ret
            } else {
                None
            }
        }
    }

    /// Accesses the Foreign V2 class immutably for a given type, if it exists (initialize it if it doesn't)
    pub fn use_class<T: ForeignItem + 'static, F, O>(&self, f: F) -> O
    where
        F: FnOnce(&VM, Option<&T::Class>) -> O,
    {
        let (update, class) = match self.classes_v2.borrow_mut().get_mut(&TypeId::of::<T>()) {
            Some(cls) => (false, cls.clone()),
            None => {
                use crate::foreign_v2::V2ClassAllocator;

                // Initialize the class (should be done in case the type is *not* constructable)
                let class = Rc::new(RefCell::new(Box::new(T::Class::allocate()) as Box<dyn Any>));
                (true, class)
            }
        };

        let ret = f(self, class.borrow().downcast_ref());

        if update {
            self.classes_v2
                .borrow_mut()
                .insert(TypeId::of::<T>(), class);
        }

        ret
    }

    /// Accesses the Foreign V2 class for a given type, if it exists (initialize it if it doesn't)
    pub fn use_class_mut<T: ForeignItem + 'static, F, O>(&self, f: F) -> O
    where
        F: FnOnce(&VM, Option<&mut T::Class>) -> O,
    {
        let (update, class) = match self.classes_v2.borrow_mut().get_mut(&TypeId::of::<T>()) {
            Some(cls) => (false, cls.clone()),
            None => {
                use crate::foreign_v2::V2ClassAllocator;

                // Initialize the class (should be done in case the type is *not* constructable)
                let class = Rc::new(RefCell::new(Box::new(T::Class::allocate()) as Box<dyn Any>));
                (true, class)
            }
        };

        let ret = f(self, class.borrow_mut().downcast_mut());

        if update {
            self.classes_v2
                .borrow_mut()
                .insert(TypeId::of::<T>(), class);
        }

        ret
    }

    /// Looks up the specified module for the given class
    /// If it's type matches with type T, will create a new instance in the given slot
    ///
    /// WARNING: This *will* overwrite slot 0, so be careful.
    pub fn set_slot_new_foreign<M: AsRef<str>, C: AsRef<str>, T: 'static + ClassObject>(
        &self, module: M, class: C, object: T, slot: SlotId,
    ) -> Result<&mut T, ForeignSendError> {
        self.set_slot_new_foreign_scratch(module, class, object, slot, 0)
    }

    /// Looks up the specified module for the given class
    /// If it's type matches with type T, will create a new instance in the given slot
    ///
    /// WARNING: This *will* overwrite slot `scratch`, so be careful.
    pub fn set_slot_new_foreign_scratch<M: AsRef<str>, C: AsRef<str>, T: 'static + ClassObject>(
        &self, module: M, class: C, object: T, slot: SlotId, scratch: SlotId,
    ) -> Result<&mut T, ForeignSendError> {
        self.ensure_slots(slot.max(scratch) + 1);
        let conf = unsafe {
            std::ptr::read_unaligned(wren_sys::wrenGetUserData(self.vm) as *mut UserData)
        };

        // Why did I put this here? (well the equivalent in the original method...)
        self.ensure_slots(slot.max(scratch) + 1);
        // Even if slot == 0, we can just load the class into slot 0, then use wrenSetSlotNewForeign to "create" a new object
        let ret = match conf
            .library
            .as_ref()
            .and_then(|lib| lib.get_foreign_class(module.as_ref(), class.as_ref()))
        {
            None => Err(ForeignSendError::NoForeignClass), // Couldn't find the corresponding class
            Some(runtime_class) => {
                if runtime_class.type_id == any::TypeId::of::<T>() {
                    // The Wren foreign class corresponds with this real object.
                    // We can coerce it and treat this object as that class, even if not instantiated by Wren.

                    // Create the new ForeignObject
                    let new_obj = ForeignObject {
                        object: Box::into_raw(Box::new(object)),
                        type_id: any::TypeId::of::<T>(),
                    };

                    // Load the Wren class object into scratch slot.
                    self.get_variable(module, class, scratch);

                    // Make sure the class isn't null (undeclared in Wren code)
                    match self.get_slot_type(scratch) {
                        SlotType::Null => Err(ForeignSendError::NoWrenClass), // You haven't declared the foreign class to Wren
                        SlotType::Unknown => unsafe {
                            // A Wren class
                            // Create the Wren foreign pointer
                            let wptr = wren_sys::wrenSetSlotNewForeign(
                                self.vm,
                                slot as raw::c_int,
                                scratch as raw::c_int,
                                mem::size_of::<ForeignObject<T>>(),
                            );

                            if !wptr.is_null() {
                                // Move the ForeignObject into the pointer
                                std::ptr::write_unaligned(wptr as *mut _, new_obj);
                            }

                            // Reinterpret the pointer as an object if we were successful
                            match (wptr as *mut ForeignObject<T>).as_mut() {
                                Some(ptr) => Ok(ptr.object.as_mut().unwrap()),
                                None => Err(ForeignSendError::NoMemory),
                            }
                        },
                        _ => Err(ForeignSendError::NoWrenClass),
                    }
                } else {
                    // The classes do not match. Avoid.
                    Err(ForeignSendError::ClassMismatch)
                }
            }
        };

        unsafe {
            std::ptr::write_unaligned(wrenGetUserData(self.vm) as *mut UserData, conf);
        }
        ret
    }

    fn make_call_handle<'b>(
        vm: *mut WrenVM, signature: FunctionSignature,
    ) -> Rc<FunctionHandle<'b>> {
        let signature =
            ffi::CString::new(signature.as_wren_string()).expect("signature conversion failed");
        Rc::new(FunctionHandle(Handle {
            handle: unsafe { wren_sys::wrenMakeCallHandle(vm, signature.as_ptr()) },
            wvm: vm,
            vm: marker::PhantomData,
        }))
    }

    pub fn abort_fiber(&self, slot: SlotId) {
        unsafe { wren_sys::wrenAbortFiber(self.vm, slot as raw::c_int) }
    }

    pub fn get_version_number(&self) -> i32 {
        unsafe { wren_sys::wrenGetVersionNumber() }
    }
}

impl Drop for VM {
    fn drop(&mut self) {
        unsafe {
            let conf = wren_sys::wrenGetUserData(self.vm);
            let _: Box<UserData> = Box::from_raw(conf as *mut _); // Drop the userdata
            wren_sys::wrenFreeVM(self.vm);
        }
    }
}