wasm_bindgen_utils_macros/
lib.rs

1use proc_macro::TokenStream;
2
3mod wasm_export;
4
5/// A proc macro that generates the wasm function bindings with `WasmEncodedResult`
6/// return type from rust functions that natively return [Result<T, E>], this makes
7/// it possible to avoid throwing on js when return value is [Result::Err] variant,
8/// instead it will return `WasmEncodedResult<T>` normally on js where either of
9/// [Result::Ok] or [Result::Err] variants are included within the `WasmEncodedResult`
10/// properties.
11///
12/// All of the `wasm_bindgen` attributes are available for this macro and are forwarded
13/// directly to `wasm_bindgen` macro on expansion.
14///
15/// Example:
16/// ```ignore
17/// use wasm_bindgen_utils::prelude::*;
18///
19/// struct TestStruct;
20///
21/// #[wasm_export]
22/// impl TestStruct {
23///     #[wasm_export(js_name = "someStaticMethod", unchecked_return_type = "string")]
24///     pub async fn some_static_method((arg1, arg2): (String, u8)) -> Result<String, Error> {
25///         Ok(String::new())
26///     }
27///     #[wasm_export(skip)]
28///     pub async fn some_skip_fn() -> Result<String, Error> {
29///         Ok(String::new())
30///     }
31///     #[some_external_macro]
32///     #[wasm_export(some_other_wbg_attrs)]
33///     pub fn some_self_method(&self, arg: String) -> Result<TestStruct, Error> {
34///         Ok(TestStruct)
35///     }
36/// }
37/// ```
38/// above will basically translate to the following:
39/// ```ignore
40/// impl TestStruct {
41///     pub async fn some_static_method((arg1, arg2): (String, u8)) -> Result<String, Error> {
42///         Ok(String::new())
43///     }
44///     pub async fn some_skip_fn() -> Result<String, Error> {
45///         Ok(String::new())
46///     }
47///     #[some_external_macro]
48///     pub fn some_self_method(&self, arg: String) -> Result<TestStruct, Error> {
49///         Ok(TestStruct)
50///     }
51/// }
52/// #[wasm_bindgen]
53/// impl TestStruct {
54///     #[wasm_bindgen(js_name = "someStaticMethod", unchecked_return_type = "WasmEncodedResult<string>")]
55///     pub async fn some_static_method__wasm_export((arg1, arg2): (String, u8)) -> WasmEncodedResult<String> {
56///         Self::some_static_method((arg1, arg2)).await.into()
57///     }
58///     #[wasm_bindgen(some_other_wbg_attrs, unchecked_return_type = "WasmEncodedResult<TestStruct>")]
59///     pub fn some_self_method__wasm_export(&self, arg: String) -> WasmEncodedResult<TestStruct> {
60///         self.some_self_method(arg).into()
61///     }
62/// }
63/// ```
64#[proc_macro_attribute]
65pub fn wasm_export(attr: TokenStream, item: TokenStream) -> TokenStream {
66    match wasm_export::expand(attr.into(), item.into()) {
67        Ok(tokens) => tokens.into(),
68        Err(e) => e.into_compile_error().into(),
69    }
70}