Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow web-sys to emit correct typescript declarations from webidl #1998

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/backend/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ pub struct ImportType {
pub rust_name: Ident,
pub js_name: String,
pub attrs: Vec<syn::Attribute>,
pub typescript_name: Option<String>,
pub doc_comment: Option<String>,
pub instanceof_shim: String,
pub is_type_of: Option<syn::Expr>,
Expand Down
17 changes: 16 additions & 1 deletion crates/backend/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,21 @@ impl ToTokens for ast::ImportType {
}
};

let description = if let Some(typescript_name) = &self.typescript_name {
let typescript_name_len = typescript_name.len() as u32;
let typescript_name_chars = typescript_name.chars().map(|c| c as u32);
quote! {
use wasm_bindgen::describe::*;
inform(NAMED_ANYREF);
inform(#typescript_name_len);
#(inform(#typescript_name_chars);)*
}
} else {
quote! {
JsValue::describe()
}
};

let is_type_of = self.is_type_of.as_ref().map(|is_type_of| {
quote! {
#[inline]
Expand Down Expand Up @@ -611,7 +626,7 @@ impl ToTokens for ast::ImportType {

impl WasmDescribe for #rust_name {
fn describe() {
JsValue::describe();
#description
}
}

Expand Down
16 changes: 13 additions & 3 deletions crates/cli-support/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ tys! {
SLICE
VECTOR
ANYREF
NAMED_ANYREF
ENUM
RUST_STRUCT
CHAR
Expand Down Expand Up @@ -62,6 +63,7 @@ pub enum Descriptor {
CachedString,
String,
Anyref,
NamedAnyref(String),
Enum { hole: u32 },
RustStruct(String),
Char,
Expand Down Expand Up @@ -134,11 +136,13 @@ impl Descriptor {
ANYREF => Descriptor::Anyref,
ENUM => Descriptor::Enum { hole: get(data) },
RUST_STRUCT => {
let name = (0..get(data))
.map(|_| char::from_u32(get(data)).unwrap())
.collect();
let name = get_string(data);
Descriptor::RustStruct(name)
}
NAMED_ANYREF => {
let name = get_string(data);
Descriptor::NamedAnyref(name)
}
CHAR => Descriptor::Char,
UNIT => Descriptor::Unit,
CLAMPED => Descriptor::_decode(data, true),
Expand Down Expand Up @@ -200,6 +204,12 @@ fn get(a: &mut &[u32]) -> u32 {
ret
}

fn get_string(data: &mut &[u32]) -> String {
(0..get(data))
.map(|_| char::from_u32(get(data)).unwrap())
.collect()
}

impl Closure {
fn decode(data: &mut &[u32]) -> Closure {
let shim_idx = get(data);
Expand Down
1 change: 1 addition & 0 deletions crates/cli-support/src/js/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1221,6 +1221,7 @@ fn adapter2ts(ty: &AdapterType, dst: &mut String) {
adapter2ts(ty, dst);
dst.push_str(" | undefined");
}
AdapterType::NamedAnyref(name) => dst.push_str(name),
AdapterType::Struct(name) => dst.push_str(name),
AdapterType::Function => dst.push_str("any"),
}
Expand Down
23 changes: 23 additions & 0 deletions crates/cli-support/src/wit/incoming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::I32],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::NamedAnyref(name.clone())],
Instruction::I32FromAnyrefOwned,
&[AdapterType::I32]
)
}
Descriptor::RustStruct(class) => {
self.instruction(
&[AdapterType::Struct(class.clone())],
Expand Down Expand Up @@ -161,6 +168,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::I32],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::NamedAnyref(name.clone())],
Instruction::I32FromAnyrefBorrow,
&[AdapterType::I32],
);
}
Descriptor::String | Descriptor::CachedString => {
// This allocation is cleaned up once it's received in Rust.
self.instruction(
Expand Down Expand Up @@ -224,6 +238,15 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::I32],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::NamedAnyref(name.clone()).option()],
Instruction::I32FromOptionAnyref {
table_and_alloc: None,
},
&[AdapterType::I32],
);
}
Descriptor::I8 => self.in_option_sentinel(AdapterType::S8),
Descriptor::U8 => self.in_option_sentinel(AdapterType::U8),
Descriptor::I16 => self.in_option_sentinel(AdapterType::S16),
Expand Down
28 changes: 28 additions & 0 deletions crates/cli-support/src/wit/outgoing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::Anyref],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::I32],
Instruction::AnyrefLoadOwned,
&[AdapterType::NamedAnyref(name.clone())],
);
}
Descriptor::I8 => self.outgoing_i32(AdapterType::S8),
Descriptor::U8 => self.outgoing_i32(AdapterType::U8),
Descriptor::I16 => self.outgoing_i32(AdapterType::S16),
Expand Down Expand Up @@ -162,6 +169,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::Anyref],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::I32],
Instruction::TableGet,
&[AdapterType::NamedAnyref(name.clone())],
);
}
Descriptor::CachedString => self.cached_string(false, false)?,

Descriptor::String => {
Expand Down Expand Up @@ -227,6 +241,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::Anyref.option()],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::I32],
Instruction::AnyrefLoadOwned,
&[AdapterType::NamedAnyref(name.clone()).option()],
);
}
Descriptor::I8 => self.out_option_sentinel(AdapterType::S8),
Descriptor::U8 => self.out_option_sentinel(AdapterType::U8),
Descriptor::I16 => self.out_option_sentinel(AdapterType::S16),
Expand Down Expand Up @@ -316,6 +337,13 @@ impl InstructionBuilder<'_, '_> {
&[AdapterType::Anyref.option()],
);
}
Descriptor::NamedAnyref(name) => {
self.instruction(
&[AdapterType::I32],
Instruction::TableGet,
&[AdapterType::NamedAnyref(name.clone()).option()],
);
}
Descriptor::CachedString => self.cached_string(true, false)?,
Descriptor::String | Descriptor::Slice(_) => {
let kind = arg.vector_kind().ok_or_else(|| {
Expand Down
5 changes: 3 additions & 2 deletions crates/cli-support/src/wit/standard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ pub enum AdapterType {
Vector(VectorKind),
Option(Box<AdapterType>),
Struct(String),
NamedAnyref(String),
Function,
}

Expand Down Expand Up @@ -322,7 +323,7 @@ impl AdapterType {
AdapterType::I64 => walrus::ValType::I64,
AdapterType::F32 => walrus::ValType::F32,
AdapterType::F64 => walrus::ValType::F64,
AdapterType::Anyref => walrus::ValType::Anyref,
AdapterType::Anyref | AdapterType::NamedAnyref(_) => walrus::ValType::Anyref,
_ => return None,
})
}
Expand All @@ -340,7 +341,7 @@ impl AdapterType {
AdapterType::F32 => wit_walrus::ValType::F32,
AdapterType::F64 => wit_walrus::ValType::F64,
AdapterType::String => wit_walrus::ValType::String,
AdapterType::Anyref => wit_walrus::ValType::Anyref,
AdapterType::Anyref | AdapterType::NamedAnyref(_) => wit_walrus::ValType::Anyref,

AdapterType::I32 => wit_walrus::ValType::I32,
AdapterType::I64 => wit_walrus::ValType::I64,
Expand Down
1 change: 1 addition & 0 deletions crates/macro-support/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ impl ConvertToAst<BindgenAttrs> for syn::ForeignItemType {
instanceof_shim: shim,
is_type_of,
rust_name: self.ident,
typescript_name: None,
js_name,
extends,
vendor_prefixes,
Expand Down
1 change: 1 addition & 0 deletions crates/typescript-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2018"

[dependencies]
wasm-bindgen = { path = '../..' }
web-sys = { path = '../web-sys', features = [ 'HtmlElement', 'Node', 'Document' ] }

[lib]
crate-type = ['cdylib']
1 change: 1 addition & 0 deletions crates/typescript-tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pub mod getters_setters;
pub mod opt_args_and_ret;
pub mod simple_fn;
pub mod simple_struct;
pub mod web_sys;
24 changes: 24 additions & 0 deletions crates/typescript-tests/src/web_sys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use wasm_bindgen::prelude::*;
use web_sys::*;

#[wasm_bindgen]
pub struct DocStruct {
doc: Document,
}

#[wasm_bindgen]
impl DocStruct {
pub fn new(doc: Document) -> Self {
Self { doc }
}

pub fn get_doc(&self) -> Document {
self.doc.clone()
}

pub fn append_element(&self, element: &HtmlElement) {
self.doc.body().unwrap().append_child(element).unwrap();
}

pub fn append_many(&self, _: &HtmlElement, _: &HtmlElement, _: &HtmlElement) {}
}
26 changes: 26 additions & 0 deletions crates/typescript-tests/src/web_sys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as wbg from "../pkg/typescript_tests";

const doc: Document = document;

const docStruct = wbg.DocStruct.new(doc);

const el: HTMLElement = document.createElement("a");

docStruct.append_element(el);
docStruct.append_many(el, el, el);

const newDoc = docStruct.get_doc();

// This test ensures that the correct Typescript types are
// used. If "newDoc" is "any", then "event" will cause the
// compilation to fail because of noImplicitAny.
newDoc.addEventListener("load", event => {
console.log(event);
});

// Same as above, but testing that the param is a document.
const listener: Parameters<
Parameters<typeof wbg["DocStruct"]["new"]>[0]["addEventListener"]
>[1] = event => console.log(event);

newDoc.addEventListener("load", listener);
1 change: 1 addition & 0 deletions crates/webidl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,7 @@ impl<'src> FirstPassRecord<'src> {
} else {
Some(syn::parse_quote! { |_| false })
},
typescript_name: Some(name.to_string()),
extends: Vec::new(),
vendor_prefixes: Vec::new(),
};
Expand Down
1 change: 1 addition & 0 deletions src/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ tys! {
SLICE
VECTOR
ANYREF
NAMED_ANYREF
ENUM
RUST_STRUCT
CHAR
Expand Down