Merge pull request #640 from alexcrichton/jscast

Implement RFC #2 - casting hierarchy between JS values
This commit is contained in:
Alex Crichton
2018-08-07 17:26:37 -05:00
committed by GitHub
14 changed files with 590 additions and 74 deletions

View File

@ -19,6 +19,7 @@
- [On JavaScript Imports](./reference/attributes/on-js-imports/index.md)
- [`catch`](./reference/attributes/on-js-imports/catch.md)
- [`constructor`](./reference/attributes/on-js-imports/constructor.md)
- [`extends`](./reference/attributes/on-js-imports/extends.md)
- [`getter` and `setter`](./reference/attributes/on-js-imports/getter-and-setter.md)
- [`indexing_getter`, `indexing_setter`, and `indexing_deleter`](./reference/attributes/on-js-imports/indexing-getter-setter-deleter.md)
- [`js_class = "Blah"`](./reference/attributes/on-js-imports/js_class.md)

View File

@ -0,0 +1,49 @@
# `extends = Class`
The `extends` attribute can be used to say that an imported type extends (in the
JS class hierarchy sense) another type. This will generate `AsRef`, `AsMut`, and
`From` impls for converting a type into another given that we statically know
the inheritance hierarchy:
```rust
#[wasm_bindgen]
extern {
type Foo;
#[wasm_bindgen(extends = Foo)]
type Bar;
}
let x: &Bar = ...;
let y: &Foo = x.as_ref(); // zero cost cast
```
The trait implementations generated for the above block are:
```rust
impl From<Bar> for Foo { ... }
impl AsRef<Foo> for Bar { ... }
impl AsMut<Foo> for Bar { ... }
```
The `extends = ...` attribute can be specified multiple times for longer
inheritance chains, and `AsRef` and such impls will be generated for each of
the types.
```rust
#[wasm_bindgen]
extern {
type Foo;
#[wasm_bindgen(extends = Foo)]
type Bar;
#[wasm_bindgen(extends = Foo, extends = Bar)]
type Baz;
}
let x: &Baz = ...;
let y1: &Bar = x.as_ref();
let y2: &Foo = x.as_ref();
```