Open jvanmalder opened 1 year ago
This solved the async problem for me:
impl From<Point> for JsValue { fn from(value: Point) -> Self { serde_wasm_bindgen::to_value(&value).unwrap() } }
Messed around with this a little more to see if I could automate the trait implementation - otherwise, each Rust structure would have to individually provide the impl block. Turns out a derive macro works great.
use proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(TsifyAsync)]
pub fn tsify_async_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_tsify_async_macro(&ast)
}
fn impl_tsify_async_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let gen = quote! {
impl From<#name> for JsValue {
fn from(value: #name) -> Self {
serde_wasm_bindgen::to_value(&value).unwrap()
}
}
};
gen.into()
}
From there we just have to add the macro as a dependency, then add TsifyAsync to the derive section of the struct.
#[derive(Debug, Serialize, Deserialize, Tsify, TsifyAsync)]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub struct Foo {
pub text: String,
pub yes_or_no: bool,
pub magic_number: i32,
}
Click to show Cargo.toml.
```toml [package] name = "asynctest" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib", "rlib"] [dependencies] tsify = "0.4.5" serde = { version = "1.0", features = ["derive"] } wasm-bindgen = { version = "0.2" } wasm-bindgen-futures = "0.4" [profile.release] # Tell `rustc` to optimize for small code size. opt-level = "s" ```Using the following code, as in the example in the README, but when using an async function to return a struct:
The compiler complains when executing
wasm-pack build --target web --release
:Both using
rustc
version1.67.1 (d5a82bbd2 2023-02-07)
and1.71.0-nightly (8b4b20836 2023-05-22)
. Saw a similar issue here but no real solution.Edit: digging a bit deeper with
cargo rustc --profile=check -- -Zunpretty=expanded
revealed the following:without
async
generates:whereas with
async
generates: