script/dom/bindings/
function.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5/// Defines a macro `native_fn!` to create a JavaScript function from a Rust function pointer.
6/// # Example
7/// ```
8/// let js_function: Rc<Function> = native_fn!(my_rust_function, c"myFunction", 2, 0);
9/// ```
10#[macro_export]
11macro_rules! native_fn {
12    ($call:expr, $name:expr, $nargs:expr, $flags:expr) => {{
13        let cx = $crate::dom::types::GlobalScope::get_cx();
14        let fun_obj = $crate::native_raw_obj_fn!(cx, $call, $name, $nargs, $flags);
15        #[allow(unsafe_code)]
16        unsafe {
17            Function::new(cx, fun_obj)
18        }
19    }};
20}
21
22/// Defines a macro `native_raw_obj_fn!` to create a raw JavaScript function object.
23/// # Example
24/// ```
25/// let raw_function_obj: *mut JSObject = native_raw_obj_fn!(cx, my_rust_function, c"myFunction", 2, 0);
26/// ```
27#[macro_export]
28macro_rules! native_raw_obj_fn {
29    ($cx:expr, $call:expr, $name:expr, $nargs:expr, $flags:expr) => {{
30        #[allow(unsafe_code)]
31        #[allow(clippy::macro_metavars_in_unsafe)]
32        unsafe extern "C" fn wrapper(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
33            $call(cx, argc, vp)
34        }
35        #[allow(unsafe_code)]
36        #[allow(clippy::macro_metavars_in_unsafe)]
37        unsafe {
38            let name: &std::ffi::CStr = $name;
39            let raw_fun = js::jsapi::JS_NewFunction(
40                *$cx,
41                Some(wrapper),
42                $nargs,
43                $flags,
44                name.as_ptr() as *const std::ffi::c_char,
45            );
46            assert!(!raw_fun.is_null());
47            js::jsapi::JS_GetFunctionObject(raw_fun)
48        }
49    }};
50}