Implement JsCast for all imported types

This commit implements the `JsCast` trait automatically for all imported types
in `#[wasm_bindgen] extern { ... }` blocks. The main change here was to generate
an `instanceof` shim for all imported types in case it's needed.

All imported types now also implement `AsRef<JsValue>` and `AsMut<JsValue>`
This commit is contained in:
Alex Crichton
2018-08-04 09:41:59 -07:00
parent f3f11ed8eb
commit 11553a1af2
9 changed files with 178 additions and 6 deletions

View File

@ -1755,7 +1755,14 @@ impl<'a, 'b> SubContext<'a, 'b> {
format!("failed to generate bindings for JS import `{}`", s.name)
})?;
}
shared::ImportKind::Type(_) => {}
shared::ImportKind::Type(ref ty) => {
self.generate_import_type(import, ty).with_context(|_| {
format!(
"failed to generate bindings for JS import `{}`",
ty.name,
)
})?;
}
shared::ImportKind::Enum(_) => {}
}
Ok(())
@ -1936,6 +1943,27 @@ impl<'a, 'b> SubContext<'a, 'b> {
Ok(())
}
fn generate_import_type(
&mut self,
info: &shared::Import,
import: &shared::ImportType,
) -> Result<(), Error> {
if !self.cx.wasm_import_needed(&import.instanceof_shim) {
return Ok(());
}
let name = self.import_name(info, &import.name)?;
self.cx.expose_get_object();
let body = format!("
function(idx) {{
return getObject(idx) instanceof {} ? 1 : 0;
}}
",
name,
);
self.cx.export(&import.instanceof_shim, &body, None);
Ok(())
}
fn generate_enum(&mut self, enum_: &shared::Enum) {
let mut variants = String::new();