| 1 |
# Communicating types to `wasm-bindgen` |
| 2 |
|
| 3 |
The last aspect to talk about when converting Rust/JS types amongst one another |
| 4 |
is how this information is actually communicated. The `#[wasm_bindgen]` macro is |
| 5 |
running over the syntactical (unresolved) structure of the Rust code and is then |
| 6 |
responsible for generating information that `wasm-bindgen` the CLI tool later |
| 7 |
reads. |
| 8 |
|
| 9 |
To accomplish this a slightly unconventional approach is taken. Static |
| 10 |
information about the structure of the Rust code is serialized via JSON |
| 11 |
(currently) to a custom section of the wasm executable. Other information, like |
| 12 |
what the types actually are, unfortunately isn't known until later in the |
| 13 |
compiler due to things like associated type projections and typedefs. It also |
| 14 |
turns out that we want to convey "rich" types like `FnMut(String, Foo, |
| 15 |
&JsValue)` to the `wasm-bindgen` CLI, and handling all this is pretty tricky! |
| 16 |
|
| 17 |
To solve this issue the `#[wasm_bindgen]` macro generates **executable |
| 18 |
functions** which "describe the type signature of an import or export". These |
| 19 |
executable functions are what the `WasmDescribe` trait is all about: |
| 20 |
|
| 21 |
```rust |
| 22 |
pub trait WasmDescribe { |
| 23 |
fn describe(); |
| 24 |
} |
| 25 |
``` |
| 26 |
|
| 27 |
While deceptively simple this trait is actually quite important. When you write, |
| 28 |
an export like this: |
| 29 |
|
| 30 |
```rust |
| 31 |
#[wasm_bindgen] |
| 32 |
fn greet(a: &str) { |
| 33 |
// ... |
| 34 |
} |
| 35 |
``` |
| 36 |
|
| 37 |
In addition to the shims we talked about above which JS generates the macro |
| 38 |
*also* generates something like: |
| 39 |
|
| 40 |
``` |
| 41 |
#[no_mangle] |
| 42 |
pub extern "C" fn __wbindgen_describe_greet() { |
| 43 |
<dyn Fn(&str)>::describe(); |
| 44 |
} |
| 45 |
``` |
| 46 |
|
| 47 |
Or in other words it generates invocations of `describe` functions. In doing so |
| 48 |
the `__wbindgen_describe_greet` shim is a programmatic description of the type |
| 49 |
layouts of an import/export. These are then executed when `wasm-bindgen` runs! |
| 50 |
These executions rely on an import called `__wbindgen_describe` which passes one |
| 51 |
`u32` to the host, and when called multiple times gives a `Vec<u32>` |
| 52 |
effectively. This `Vec<u32>` can then be reparsed into an `enum Descriptor` |
| 53 |
which fully describes a type. |
| 54 |
|
| 55 |
All in all this is a bit roundabout but shouldn't have any impact on the |
| 56 |
generated code or runtime at all. All these descriptor functions are pruned from |
| 57 |
the emitted wasm file. |