Allow for js property inspection (#1876)

* Add support for #[wasm_bindgen(inspectable)]

This annotation generates a `toJSON` and `toString` implementation for
generated JavaScript classes which display all readable properties
available via the class or its getters

This is useful because wasm-bindgen classes currently serialize to
display one value named `ptr`, which does not model the properties of
the struct in Rust

This annotation addresses rustwasm/wasm-bindgen#1857

* Support console.log for inspectable attr in Nodejs

`#[wasm_bindgen(inspectable)]` now generates an implementation of
`[util.inspect.custom]` for the Node.js target only. This implementation
causes `console.log` and friends to yield the same class-style output,
but with all readable fields of the Rust struct displayed

* Reduce duplication in generated methods

Generated `toString` and `[util.inspect.custom]` methods now call
`toJSON` to reduce duplication

* Store module name in variable
This commit is contained in:
Katie
2019-11-26 10:39:57 -08:00
committed by Alex Crichton
parent 181b10be3f
commit df34cf843e
9 changed files with 228 additions and 0 deletions

View File

@ -45,6 +45,7 @@ macro_rules! attrgen {
(readonly, Readonly(Span)),
(js_name, JsName(Span, String, Span)),
(js_class, JsClass(Span, String, Span)),
(inspectable, Inspectable(Span)),
(is_type_of, IsTypeOf(Span, syn::Expr)),
(extends, Extends(Span, syn::Path)),
(vendor_prefix, VendorPrefix(Span, Ident)),
@ -322,6 +323,7 @@ impl<'a> ConvertToAst<BindgenAttrs> for &'a mut syn::ItemStruct {
.js_name()
.map(|s| s.0.to_string())
.unwrap_or(self.ident.to_string());
let is_inspectable = attrs.inspectable().is_some();
for (i, field) in self.fields.iter_mut().enumerate() {
match field.vis {
syn::Visibility::Public(..) => {}
@ -361,6 +363,7 @@ impl<'a> ConvertToAst<BindgenAttrs> for &'a mut syn::ItemStruct {
js_name,
fields,
comments,
is_inspectable,
})
}
}