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
use proc_macro::{TokenStream};

use quote::quote;
use syn::ItemFn;

#[proc_macro_attribute]
pub fn entrypoint(_attr: TokenStream, mut item: TokenStream) -> TokenStream {
	let input: ItemFn = syn::parse(item.clone()).unwrap();
	let name = input.sig.ident;

	let gen = quote! {
		#[no_mangle]
		pub extern "C" fn mexFunction(nlhs: ::std::os::raw::c_int, lhs: *mut *mut ::rustmex::mxArray,
						nrhs: ::std::os::raw::c_int, rhs: *const *const ::rustmex::mxArray) {

			// SAFETY: it is UB to unwind over FFI boundaries; we must
			// therefore catch an unwinding panic here.
			match std::panic::catch_unwind(|| {
				let rhslice = unsafe { ::std::slice::from_raw_parts(rhs as *const &::rustmex::mxArray, nrhs as usize) };
				let lhslice = unsafe { ::std::slice::from_raw_parts_mut(lhs as *mut Option<&mut ::rustmex::mxArray>, nlhs as usize) };

				// SAFETY: Transmuting to an MxArray is safe, since both it and
				// NonNull are repr(transparent).
				//
				// Also NOTE that transmute does nothing if Lhs is from before
				// v0.1.3, since where then doing transmute<T, T>.
				let lhslice_owned = unsafe { ::std::mem::transmute(lhslice) };

				match #name(lhslice_owned, rhslice) {
					Ok(_) => return,
					Err(e) => ::rustmex::trigger_error!(e)
				}
			}) {
				Ok(_) => return,
				Err(_) => {
					::rustmex::trigger_error!(::rustmex::message::AdHoc(
						"rustmex:panic",
						"The MEX function you called paniced. Consider restarting your interpreter with an appropriate value of RUST_BACKTRACE (setenv does not seem to work)"
					));
				}
			}
		}
	};
	let entrypoint: TokenStream = gen.into();
	item.extend(entrypoint);
	item
}