Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why does #[wasm_bindgen] allow &T in synchronous functions but not in async functions? #4388

Closed
cspinetta opened this issue Dec 31, 2024 · 1 comment
Labels

Comments

@cspinetta
Copy link

Summary

I'm encountering an issue when using #[wasm_bindgen] with functions that accept references (&T). Here's a simplified example:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn sync_function(x: &ExportedNamedStruct) {
    println!("sync_function: {:?}", x);
}

The above code works fine, and I can call sync_function from JavaScript without any issues. However, when I make the function async:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub async fn async_function(x: &ExportedNamedStruct) {
    println!("async_function: {:?}", x);
}

I get the following error:

error[E0433]: failed to resolve: could not find `borrow` in `core`
  --> src/lib.rs:20:1
   |
20 | #[wasm_bindgen]
   | ^^^^^^^^^^^^^^^ could not find `borrow` in `core`
   |
   = note: this error originates in the attribute macro `wasm_bindgen` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider importing this module
   |
6  + use std::borrow;
   |

From my understanding, wasm-bindgen supports borrowing (&T) in synchronous functions (as specified here), but this does not seem to extend to async functions. I assume this limitation is due to how Rust manages lifetimes and how WebAssembly ABI works, especially with async functions potentially suspending execution.

Questions:

  • Could you provide insights into why wasm-bindgen does not support &T in async functions?
  • Are there any best practices or idiomatic patterns for handling this situation?
  • Are there plans to support this in the future?

Additional Details

  • Rust version: 1.82.0
  • wasm-bindgen version: 0.2.95

Example Struct:

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
#[derive(Debug)]
pub struct ExportedNamedStruct {
    pub inner: u32,
}

Thank you for your time and insights!

@daxpedda
Copy link
Collaborator

daxpedda commented Jan 4, 2025

It seems to me that the issue is rather that the proc-macro generates some invalid path to core::borrow. So it probably got fixed by #4005. In any case, this should work and I was unable to produce the same error with the newest version!

Try updating wasm-bindgen, but please let me know if this didn't fix the issue for you!

@daxpedda daxpedda closed this as not planned Won't fix, can't repro, duplicate, stale Jan 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants