macro_wasmer_universal_test/
lib.rs

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
use proc_macro2::{Ident, Span, TokenStream};
use syn::{
    parse::{Parse, ParseStream},
    Attribute, Signature, Visibility,
};

#[proc_macro_attribute]
pub fn universal_test(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let MaybeItemFn {
        outer_attrs,
        inner_attrs,
        vis,
        sig,
        block,
    } = syn::parse_macro_input!(item as MaybeItemFn);

    let fn_call = Ident::new(&sig.ident.to_string(), Span::call_site());
    let fn_js_call = Ident::new(&format!("{}_js", sig.ident), Span::call_site());

    let tokens = quote::quote! {
        #[cfg(feature = "js")]
        #[cfg_attr(feature = "js", wasm_bindgen_test)]
        #(#outer_attrs) *
        fn #fn_js_call() { #fn_call().unwrap(); }

        #[cfg_attr(any(feature = "sys", feature = "jsc", feature = "wasm-c-api"), test)]
        #(#outer_attrs) *
        #vis #sig
        {
            #(#inner_attrs) *
            #block
        }
    };

    proc_macro::TokenStream::from(tokens)
}

// ---- Taken from tracing::instrument ----
// This is a more flexible/imprecise `ItemFn` type,
// which's block is just a `TokenStream` (it may contain invalid code).
#[derive(Debug, Clone)]
struct MaybeItemFn {
    outer_attrs: Vec<Attribute>,
    inner_attrs: Vec<Attribute>,
    vis: Visibility,
    sig: Signature,
    block: TokenStream,
}

/// This parses a `TokenStream` into a `MaybeItemFn`
/// (just like `ItemFn`, but skips parsing the body).
impl Parse for MaybeItemFn {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let outer_attrs = input.call(Attribute::parse_outer)?;
        let vis: Visibility = input.parse()?;
        let sig: Signature = input.parse()?;
        let inner_attrs = input.call(Attribute::parse_inner)?;
        let block: TokenStream = input.parse()?;
        Ok(Self {
            outer_attrs,
            inner_attrs,
            vis,
            sig,
            block,
        })
    }
}