Allow returning Result from functions

This commit adds support for exporting a function defined in Rust that returns a
`Result`, translating the `Ok` variant to the actual return value and the `Err`
variant to an exception that's thrown in JS.

The support for return types and descriptors was rejiggered a bit to be a bit
more abstract and more well suited for this purpose. We no longer distinguish
between functions with a return value and those without a return value.
Additionally a new trait, `ReturnWasmAbi`, is used for converting return values.
This trait is an internal implementation detail, however, and shouldn't surface
itself to users much (if at all).

Closes #841
This commit is contained in:
Alex Crichton
2018-09-17 18:26:45 -07:00
parent ccced83b0e
commit 7cf4213283
17 changed files with 292 additions and 266 deletions

View File

@ -30,6 +30,7 @@
- [`String`](./reference/types/string.md)
- [Number Slices](./reference/types/number-slices.md)
- [Boxed Number Slices](./reference/types/boxed-number-slices.md)
- [`Result<T, JsValue>`](./reference/types/result.md)
- [`#[wasm_bindgen]` Attributes](./reference/attributes/index.md)
- [On JavaScript Imports](./reference/attributes/on-js-imports/index.md)
- [`catch`](./reference/attributes/on-js-imports/catch.md)

View File

@ -0,0 +1,20 @@
# `Result<T, JsValue>`
| `T` parameter | `&T` parameter | `&mut T` parameter | `T` return value | `Option<T>` parameter | `Option<T>` return value | JavaScript representation |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| No | No | No | No | No | Yes | Same as `T`, or an exception |
The `Result` type can be returned from functions exported to JS as well as
closures in Rust. Only `Result<T, JsValue>` is supported where `T` can be
converted to JS. Whenever `Ok(val)` is encountered it's converted to JS and
handed off, and whenever `Err(error)` is encountered an exception is thrown in
JS with `error`.
You can use `Result` to enable handling of JS exceptions with `?` in Rust,
naturally propagating it upwards to the wasm boundary. Furthermore you can also
return custom types in Rust so long as they're all convertible to `JsValue`.
Note that if you import a JS function with `Result` you need
`#[wasm_bindgen(catch)]` to be annotated on the import (unlike exported
functions, which require no extra annotation). This may not be necessary in the
future though and it may work "as is"!.