1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
use proc_macro2::*;
use std::sync::atomic::*;
static CNT: AtomicUsize = AtomicUsize::new(0);
#[proc_macro_attribute]
pub fn wasm_bindgen_test(
attr: proc_macro::TokenStream,
body: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let mut attr = attr.into_iter();
let mut async = false;
while let Some(token) = attr.next() {
match &token {
proc_macro::TokenTree::Ident(i) if i.to_string() == "async" => async = true,
_ => panic!("malformed `#[wasm_bindgen_test]` attribute"),
}
match &attr.next() {
Some(proc_macro::TokenTree::Punct(op)) if op.as_char() == ',' => {}
Some(_) => panic!("malformed `#[wasm_bindgen_test]` attribute"),
None => break,
}
}
let mut body = TokenStream::from(body).into_iter();
let mut leading_tokens = Vec::new();
while let Some(token) = body.next() {
leading_tokens.push(token.clone());
if let TokenTree::Ident(token) = token {
if token == "fn" {
break;
}
}
}
let ident = match body.next() {
Some(TokenTree::Ident(token)) => token,
_ => panic!("expected a function name"),
};
let mut tokens = Vec::<TokenTree>::new();
let test_body = if async {
quote! { cx.execute_async(test_name, #ident); }
} else {
quote! { cx.execute_sync(test_name, #ident); }
};
let name = format!(
"__wbg_test_{}_{}",
ident,
CNT.fetch_add(1, Ordering::SeqCst)
);
let name = Ident::new(&name, Span::call_site());
tokens.extend(
(quote! {
#[no_mangle]
pub extern "C" fn #name(cx: *const ::wasm_bindgen_test::__rt::Context) {
unsafe {
let cx = &*cx;
let test_name = concat!(module_path!(), "::", stringify!(#ident));
#test_body
}
}
})
.into_iter(),
);
tokens.extend(leading_tokens);
tokens.push(ident.into());
tokens.extend(body);
tokens.into_iter().collect::<TokenStream>().into()
}