2

I've been reading the Rust Wasm Book lately. In it, it utilizes wasm_bindgen through #[wasm_bindgen] annotations. In section 5.5 "Debugging", the following is mentioned:

Note that in order to run the #[test]s without compiler and linker errors, you will need to comment out the crate-type = "cdylib" bits in wasm-game-of-life/Cargo.toml.

It similarly recommends commenting out the #[wasm-bindgen] attributes on methods/structs in the next section while running bench tests.

To add an even more complicated portion to this, there are sections like this in complicated wasm applications:

#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = performance)]
    fn now() -> f64;
}

I've needed to comment out these sections, as well, in order to get the code to run natively.

This, of course, seems super tedious. My question is whether there is a way to do this work automatically, via the compiler (or via a cargo script), so that I can specify a command such as cargo build or cargo test, which will compile natively (with the attributes disabled), and perhaps something like cargo build --feature=wasm to build with wasm_bindgen enabled.

I thought about writing a separate build.rs script that copies over all sources and Cargo.toml files to an intermediate directory (so your source code isn't modified in place), does the commenting itself, and then builds from this source. Of course, the problem here is that 1) the build script is editing your source, so the line numbers will be off, and 2) it seems unclean - a hacky way to get around this problem.

I was wondering if others had suggestions I could use or things they have used, as this seems like pretty desirable behavior.

jwir3
  • 6,019
  • 5
  • 47
  • 92
  • It's actually slightly more complicated than that, because there are also `extern` definitions that would need to be compiled out. – jwir3 Oct 22 '18 at 15:15
  • 2
    Does [this](https://stackoverflow.com/questions/42551113/is-it-possible-to-conditionally-enable-an-attribute-like-derive/42551386) help you? Specifically: `#[cfg_attr(not(test), wasm_bindgen(js_namespace = performance))]`. This would disable the attribute for tests. Similarly you can just put `#[cfg(not(test))]` on your `extern` block to completely remove it if you are not compiling for testing. If this is what you are searching for, I can make an answer out of this. – Lukas Kalbertodt Oct 22 '18 at 15:26
  • I'm not sure that the `cfg_attr` is the solution. Unless the whole ecosystem starts using it for each attribute, that does not solve the problem of uniformly disabling wasm-bindgen across all the dependencies. – axel22 Mar 12 '21 at 15:12

0 Answers0