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
#[cfg(not(feature = "no-std"))]
static PANIC_HANDLER_INIT: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

#[cfg(not(feature = "no-std"))]
#[doc(hidden)]
pub fn initial_setup() {
    if PANIC_HANDLER_INIT
        .compare_exchange(
            false,
            true,
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
        )
        .is_err()
    {
        return;
    }

    unsafe {
        ocaml_boxroot_sys::boxroot_setup();
    }

    ::std::panic::set_hook(Box::new(|info| unsafe {
        let err = info.payload();
        let msg = if err.is::<&str>() {
            err.downcast_ref::<&str>().unwrap().to_string()
        } else if err.is::<String>() {
            err.downcast_ref::<String>().unwrap().clone()
        } else {
            format!("{:?}", err)
        };

        if let Some(err) = crate::Value::named("Rust_exception") {
            crate::Error::raise_value(err, &msg);
        }

        crate::Error::raise_failure(&msg)
    }))
}

/// `body!` is needed to help the OCaml runtime to manage garbage collection, it should
/// be used to wrap the body of each function exported to OCaml. Panics from Rust code
/// will automatically be unwound/caught here (unless the `no-std` feature is enabled)
///
/// ```rust
/// #[no_mangle]
/// pub unsafe extern "C" fn example(a: ocaml::Value, b: ocaml::Value) -> ocaml::Value {
///     ocaml::body!(gc: {
///         let a = a.int_val();
///         let b = b.int_val();
///         ocaml::Value::int(a + b)
///     })
/// }
/// ```
#[macro_export]
#[cfg(not(feature = "no-std"))]
macro_rules! body {
    ($gc:ident: $code:block) => {{
        let $gc = unsafe { $crate::Runtime::recover_handle() };

        // Ensure panic handler is initialized
        #[cfg(not(feature = "no-std"))]
        $crate::initial_setup();

        {
            $code
        }
    }};
}

#[macro_export]
/// Convenience macro to create an OCaml array
macro_rules! array {
    ($($x:expr),*) => {{
        $crate::ToValue::to_value(&vec![$($crate::ToValue::to_value(&$x)),*])
    }}
}

#[macro_export]
/// Convenience macro to create an OCaml list
macro_rules! list {
    ($($x:expr),*) => {{
        let mut l = $crate::list::empty();
        for i in (&[$($x),*]).into_iter().rev() {
            $crate::list::push_hd(&mut l, $crate::ToValue::to_value(i));
        }
        l
    }};
}

#[macro_export]
/// Import OCaml functions
macro_rules! import {
    ($vis:vis fn $name:ident($($arg:ident: $t:ty),*) $(-> $r:ty)?) => {
        $vis unsafe fn $name(rt: &$crate::Runtime, $($arg: $t),*) -> Result<$crate::interop::default_to_unit!($($r)?), $crate::Error> {
            use $crate::{ToValue, FromValue};
            type R = $crate::interop::default_to_unit!($($r)?);
            let ocaml_rs_named_func = match $crate::Value::named(stringify!($name)) {
                Some(x) => x,
                None => {
                    let msg = concat!(
                        stringify!($name),
                        " has not been registered using Callback.register"
                    );
                    return Err($crate::Error::Message(msg));
                },
            };
            $(let $arg = $arg.to_value(rt);)*
            let __unit = [$crate::Value::unit().raw()];
            let __args = [$($arg.raw()),*];
            let mut args = __args.as_slice();
            if args.is_empty() {
                args = &__unit;
            }
            let x = ocaml_rs_named_func.call_n(args)?;
            Ok(R::from_value(x))
        }
    };
    ($($vis:vis fn $name:ident($($arg:ident: $t:ty),*) $(-> $r:ty)?;)+) => {
        $(
            $crate::import!($vis fn $name($($arg: $t),*) $(-> $r)?);
        )*
    }
}