wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

Warning / lints around holding borrows across await points?

Open rksm opened this issue 9 months ago • 0 comments

Hello, first let me say, wasm-bindgen is awesome and it provides such a great experience of writing Rust in the browser and JS environments. Thanks to everyone involved and contributing!


Here is my question regarding an improvement around wasm-bindgen async ergonomics: In my project we've recently run into a case where we had a method like

#[wasm_bindgen]
pub async fn some_method(&mut self) {
    something.await;
}

The JavaScript code called this concurrently which lead to panics of the kind "recursive use of an object detected which would lead to unsafe aliasing in rust". This was surprising as the wasm_bindgen interface does not reveal the fact that self is being borrowed from a WasmRefCell.

In "normal" Rust code, the clippy lint await_holding_refcell_ref will warn about this behavior With wasm_bindgen the author not only needs to be aware of these semantics, they also need to know about the wasm_bindgen implementation. On top, this issue might only manifest itself in certain (race) conditions (like in our case), making narrowing it down just the harder.

We also don't seem to be the first to have stumbled across this:

  • https://github.com/rustwasm/wasm-bindgen/discussions/3660
  • https://github.com/rustwasm/wasm-bindgen/issues/3091
  • https://www.rossng.eu/posts/2025-01-20-wasm-bindgen-pitfalls/#pitfall-2-holding-mutable-references-across-await

So here is my question:

Would it make sense to provide a lint for this behavior or maybe warn about this in other ways, e.g. through the code generated with the macro? The current behavior can be really surprising and seems to contradict the otherwise very explicit nature of Rust.

rksm avatar Feb 22 '25 11:02 rksm