Skip to main content

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    ($cx:expr, $call:expr, $name:expr, $nargs:expr, $flags:expr) => {{
13        let fun_obj = $crate::native_raw_obj_fn!($cx, $call, $name, $nargs, $flags);
14        let cx = $cx;
15        #[expect(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        #[expect(unsafe_code)]
31        #[allow(clippy::macro_metavars_in_unsafe)]
32        unsafe extern "C" fn wrapper(
33            cx: *mut js::jsapi::JSContext,
34            argc: u32,
35            vp: *mut JSVal,
36        ) -> bool {
37            let mut cx = unsafe {
38                // SAFETY: We are in SM hook
39                js::context::JSContext::from_ptr(
40                    std::ptr::NonNull::new(cx).expect("JSContext is not null in SM hook"),
41                )
42            };
43            let call_args = unsafe { CallArgs::from_vp(vp, argc) };
44            $call(&mut cx, call_args)
45        }
46        #[expect(unsafe_code)]
47        #[allow(clippy::macro_metavars_in_unsafe)]
48        unsafe {
49            let name: &std::ffi::CStr = $name;
50            let raw_fun = js::rust::wrappers2::JS_NewFunction(
51                $cx,
52                Some(wrapper),
53                $nargs,
54                $flags,
55                name.as_ptr(),
56            );
57            assert!(!raw_fun.is_null());
58            js::jsapi::JS_GetFunctionObject(raw_fun)
59        }
60    }};
61}