Skip to content

Typescript Generic Types #4455

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
111 changes: 100 additions & 11 deletions crates/backend/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use quote::{quote, ToTokens};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use syn::parse_quote;
use syn::spanned::Spanned;
use wasm_bindgen_shared as shared;
use syn::{spanned::Spanned, PathArguments, PathSegment, Type};
use wasm_bindgen_shared::{self as shared, identifier::TYPE_DESCRIBE_MAP};

/// A trait for converting AST structs into Tokens and adding them to a TokenStream,
/// or providing a diagnostic if conversion fails.
Expand Down Expand Up @@ -863,22 +863,30 @@ impl TryToTokens for ast::Export {
})
.to_tokens(into);

let mut args_ty_map = Vec::new();
let describe_args: TokenStream = argtys
.iter()
.map(|ty| match ty {
syn::Type::Reference(reference)
if self.function.r#async && reference.mutability.is_none() =>
{
let inner = &reference.elem;
quote! {
inform(LONGREF);
<#inner as WasmDescribe>::describe();
.map(|ty| {
args_ty_map.push(map_type_describe(ty));
match ty {
syn::Type::Reference(reference)
if self.function.r#async && reference.mutability.is_none() =>
{
let inner = &reference.elem;
quote! {
inform(LONGREF);
<#inner as WasmDescribe>::describe();
}
}
_ => quote! { <#ty as WasmDescribe>::describe(); },
}
_ => quote! { <#ty as WasmDescribe>::describe(); },
})
.collect();

// build the return type map and args type map
let ret_ty_map = map_type_describe(syn_ret);
let args_ty_map: TokenStream = args_ty_map.into_iter().collect();

// In addition to generating the shim function above which is what
// our generated JS will invoke, we *also* generate a "descriptor"
// shim. This descriptor shim uses the `WasmDescribe` trait to
Expand All @@ -904,6 +912,10 @@ impl TryToTokens for ast::Export {
inform(#nargs);
#describe_args
#describe_ret
inform(#TYPE_DESCRIBE_MAP);
#ret_ty_map
inform(#TYPE_DESCRIBE_MAP);
#args_ty_map
},
attrs: attrs.clone(),
wasm_bindgen: &self.wasm_bindgen,
Expand Down Expand Up @@ -1986,3 +1998,80 @@ fn respan(input: TokenStream, span: &dyn ToTokens) -> TokenStream {
}
new_tokens.into_iter().collect()
}

/// Recursively maps the given type to its WasmDescribe sequence
pub fn map_type_describe(typ: &Type) -> TokenStream {
let default = quote! {
inform(0u32);
inform(EXTERNREF);
};
match typ {
Type::Path(type_path) => {
if let Some(PathSegment { ident, arguments }) = &type_path.path.segments.last() {
match arguments {
// this is the end point where a type has no more nested types
PathArguments::None => quote! {
inform(0u32);
<#type_path as WasmDescribe>::describe();
},
PathArguments::AngleBracketed(angle_bracket) => {
// process each generic type recursively
let mut len = angle_bracket.args.len() as u32;
// for "Result" the second arg usually does not impl WasmDescribe
// and is not needed for ts typings either, so we skip over it
if ident == "Result" {
len -= 1;
};
let mut generics = vec![quote! {
inform(#len);
<#type_path as WasmDescribe>::describe();
}];
for arg in &angle_bracket.args {
if len == 0 {
break;
}
if let syn::GenericArgument::Type(generic) = arg {
generics.push(map_type_describe(generic));
}
len -= 1;
}
generics.into_iter().collect()
}
PathArguments::Parenthesized(_) => default,
}
} else {
default
}
}
Type::Ptr(type_ptr) => map_type_describe(&type_ptr.elem),
Type::Reference(type_reference) => map_type_describe(&type_reference.elem),
Type::Paren(type_paren) => map_type_describe(&type_paren.elem),
Type::Array(type_array) => {
let inner = map_type_describe(&type_array.elem);
quote! {
inform(1);
<#type_array as WasmDescribe>::describe();
#inner
}
}
Type::Slice(type_slice) => {
let inner = map_type_describe(&type_slice.elem);
quote! {
inform(1);
<#type_slice as WasmDescribe>::describe();
#inner
}
}
Type::Tuple(type_tuple) => {
if type_tuple.elems.is_empty() {
quote! {
inform(0);
<#type_tuple as WasmDescribe>::describe();
}
} else {
default
}
}
_ => default,
}
}
65 changes: 58 additions & 7 deletions crates/cli-support/src/descriptor.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::char;

use wasm_bindgen_shared::identifier::is_valid_ident;
use wasm_bindgen_shared::identifier::{is_valid_ident, TYPE_DESCRIBE_MAP};

macro_rules! tys {
($($a:ident)*) => (tys! { @ ($($a)*) 0 });
Expand Down Expand Up @@ -89,6 +89,10 @@ pub enum Descriptor {
Result(Box<Descriptor>),
Unit,
NonNull,
Generic {
ty: Box<Descriptor>,
args: Box<[Descriptor]>,
},
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand All @@ -97,6 +101,8 @@ pub struct Function {
pub shim_idx: u32,
pub ret: Descriptor,
pub inner_ret: Option<Descriptor>,
pub inner_ret_map: Option<Descriptor>,
pub args_ty_map: Option<Vec<Descriptor>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -279,20 +285,46 @@ impl Closure {
impl Function {
fn decode(data: &mut &[u32]) -> Function {
let shim_idx = get(data);
let arguments = (0..get(data))
let args_len = get(data);
let arguments = (0..args_len)
.map(|_| Descriptor::_decode(data, false))
.collect::<Vec<_>>();
let ret = Descriptor::_decode(data, false);
let inner_ret = Some(Descriptor::_decode(data, false));

// decode inner retrun type map
let inner_ret_map = if !data.is_empty() && data[0] == TYPE_DESCRIBE_MAP {
get(data);
Some(decode_ty_map(data))
} else {
None
};

// decode args type map
let args_ty_map = if !data.is_empty() && data[0] == TYPE_DESCRIBE_MAP {
get(data);
let mut args = vec![];
for _i in 0..args_len {
args.push(decode_ty_map(data));
}
Some(args)
} else {
None
};

Function {
arguments,
shim_idx,
ret: Descriptor::_decode(data, false),
inner_ret: Some(Descriptor::_decode(data, false)),
ret,
inner_ret,
inner_ret_map,
args_ty_map,
}
}
}

impl VectorKind {
pub fn js_ty(&self) -> String {
pub fn js_ty(&self, generics: Option<String>) -> String {
match *self {
VectorKind::String => "string".to_string(),
VectorKind::I8 => "Int8Array".to_string(),
Expand All @@ -309,9 +341,9 @@ impl VectorKind {
VectorKind::Externref => "any[]".to_string(),
VectorKind::NamedExternref(ref name) => {
if is_valid_ident(name.as_str()) {
format!("{}[]", name)
format!("{}{}[]", name, generics.unwrap_or_default())
} else {
format!("({})[]", name)
format!("({}){}[]", name, generics.unwrap_or_default())
}
}
}
Expand All @@ -336,3 +368,22 @@ impl VectorKind {
}
}
}

/// Decodes a type map recursively to a Descriptor
/// Type map is a tree like structure of a type's wasm describes
pub fn decode_ty_map(data: &mut &[u32]) -> Descriptor {
let len = get(data);
let ty = Descriptor::_decode(data, false);
if len == 0 {
ty
} else {
let mut args = vec![];
for _i in 0..len {
args.push(decode_ty_map(data));
}
Descriptor::Generic {
ty: Box::new(ty),
args: args.into_boxed_slice(),
}
}
}
4 changes: 3 additions & 1 deletion crates/cli-support/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ macro_rules! intrinsics {
shim_idx: 0,
arguments: vec![$($arg),*],
ret: $ret,
inner_ret: None
inner_ret: None,
inner_ret_map: None,
args_ty_map: None,
}
}
)*
Expand Down
Loading
Loading