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
//! Macros for [`relay-ffi`].
//!
//! [`relay-ffi`]: ../relay_ffi/index.html

#![warn(missing_docs)]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png",
    html_favicon_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png"
)]
#![allow(clippy::derive_partial_eq_without_eq)]

use proc_macro::TokenStream;
use quote::ToTokens;
use syn::fold::Fold;

struct CatchUnwind;

impl CatchUnwind {
    fn fold(&mut self, input: TokenStream) -> TokenStream {
        let f = syn::parse(input).expect("#[catch_unwind] can only be applied to functions");
        self.fold_item_fn(f).to_token_stream().into()
    }
}

impl Fold for CatchUnwind {
    fn fold_item_fn(&mut self, i: syn::ItemFn) -> syn::ItemFn {
        if i.sig.unsafety.is_none() {
            panic!("#[catch_unwind] requires `unsafe fn`");
        }

        let inner = i.block;
        let folded = quote::quote! {{
            ::relay_ffi::__internal::catch_errors(|| {
                let __ret = #inner;

                #[allow(unreachable_code)]
                Ok(__ret)
            })
        }};

        let block = Box::new(syn::parse2(folded).unwrap());
        syn::ItemFn { block, ..i }
    }
}

/// Captures errors and panics in a thread-local on `unsafe` functions.
///
/// See [`relay-ffi` documentation] for more information.
///
/// # Examples
///
/// ```ignore
/// use relay_ffi::catch_unwind;
///
/// #[no_mangle]
/// #[catch_unwind]
/// pub unsafe extern "C" fn run_ffi() -> i32 {
///     "invalid".parse()?
/// }
/// ```
///
/// [`relay-ffi` documentation]: ../relay_ffi/index.html
#[proc_macro_attribute]
pub fn catch_unwind(_attr: TokenStream, item: TokenStream) -> TokenStream {
    CatchUnwind.fold(item)
}