Skip to content

Commit 911a32c

Browse files
committed
Add the #[wasm_bindgen(static_method_of = Class)] attribute
This is similar to `js_namespace` but translates into a static method on `Class` rather than a free function. This allows us to have bindings to things like `Object.keys` as `Object::keys`.
1 parent 56fa901 commit 911a32c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

crates/backend/src/ast.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
22
use quote::ToTokens;
33
use shared;
4+
use std::iter::FromIterator;
45
use syn;
56

67
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
@@ -412,6 +413,24 @@ impl Program {
412413
ty: class.clone(),
413414
kind: MethodKind::Normal,
414415
}
416+
} else if let Some(cls) = wasm.opts.static_method_of() {
417+
let class = cls.to_string();
418+
let kind = MethodKind::Static;
419+
420+
let segments = syn::punctuated::Punctuated::from_iter(Some(syn::PathSegment {
421+
ident: cls.clone(),
422+
arguments: syn::PathArguments::None,
423+
}));
424+
425+
let ty = syn::Type::Path(syn::TypePath {
426+
qself: None,
427+
path: syn::Path {
428+
leading_colon: None,
429+
segments,
430+
},
431+
});
432+
433+
ImportFunctionKind::Method { class, ty, kind }
415434
} else if wasm.opts.constructor() {
416435
let class = match wasm.ret {
417436
Some(ref ty) => ty,
@@ -888,6 +907,16 @@ impl BindgenAttrs {
888907
})
889908
}
890909

910+
fn static_method_of(&self) -> Option<&Ident> {
911+
self.attrs
912+
.iter()
913+
.filter_map(|a| match a {
914+
BindgenAttr::StaticMethodOf(c) => Some(c),
915+
_ => None
916+
})
917+
.next()
918+
}
919+
891920
fn method(&self) -> bool {
892921
self.attrs.iter().any(|a| match a {
893922
BindgenAttr::Method => true,
@@ -980,6 +1009,7 @@ pub enum BindgenAttr {
9801009
Catch,
9811010
Constructor,
9821011
Method,
1012+
StaticMethodOf(Ident),
9831013
JsNamespace(Ident),
9841014
Module(String),
9851015
Version(String),
@@ -999,6 +1029,13 @@ impl syn::synom::Synom for BindgenAttr {
9991029
|
10001030
call!(term, "method") => { |_| BindgenAttr::Method }
10011031
|
1032+
do_parse!(
1033+
call!(term, "static_method_of") >>
1034+
punct!(=) >>
1035+
cls: call!(term2ident) >>
1036+
(cls)
1037+
)=> { BindgenAttr::StaticMethodOf }
1038+
|
10021039
do_parse!(
10031040
call!(term, "getter") >>
10041041
val: option!(do_parse!(

0 commit comments

Comments
 (0)