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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#![doc = include_str!("../README.md")]

use proc_macro::TokenStream;
use quote::{quote, quote_spanned};

#[derive(Clone, Copy)]
enum Platform {
    Default,
    Tokio,
    AsyncStd,
    Dfir,
    Wasm,
    EnvLogging,
    EnvTracing,
}
impl Platform {
    // All platforms.
    const ALL: [Self; 7] = [
        Self::Default,
        Self::Tokio,
        Self::AsyncStd,
        Self::Dfir,
        Self::Wasm,
        Self::EnvLogging,
        Self::EnvTracing,
    ];
    // Default when no platforms are specified.
    const DEFAULT: [Self; 2] = [Self::Default, Self::Wasm];

    /// Name of platform ident in attribute.
    const fn name(self) -> &'static str {
        match self {
            Self::Default => "test",
            Self::Tokio => "tokio",
            Self::AsyncStd => "async_std",
            Self::Dfir => "dfir",
            Self::Wasm => "wasm",
            Self::EnvLogging => "env_logging",
            Self::EnvTracing => "env_tracing",
        }
    }

    /// Generate the attribute for this platform (if any).
    fn make_attribute(self) -> proc_macro2::TokenStream {
        // Fully specify crate names so that the consumer does not need to add another
        // use statement. They still need to depend on the crate in their `Cargo.toml`,
        // though.
        // TODO(mingwei): use `proc_macro_crate::crate_name(...)` to handle renames.
        match self {
            Platform::Default => quote! { #[test] },
            Platform::Tokio => quote! { #[tokio::test ] },
            Platform::AsyncStd => quote! { #[async_std::test] },
            Platform::Dfir => quote! { #[dfir_rs::test] },
            Platform::Wasm => {
                quote! { #[wasm_bindgen_test::wasm_bindgen_test] }
            }
            Platform::EnvLogging | Platform::EnvTracing => Default::default(),
        }
    }

    /// Generate the initialization code statements for this platform (if any).
    fn make_init_code(self) -> proc_macro2::TokenStream {
        match self {
            Platform::EnvLogging => quote! {
                let _ = env_logger::builder().is_test(true).try_init();
            },
            Platform::EnvTracing => quote! {
                let subscriber = tracing_subscriber::FmtSubscriber::builder()
                    .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
                    .with_test_writer()
                    .finish();
                let _ = tracing::subscriber::set_global_default(subscriber);
            },
            _ => Default::default(),
        }
    }
}

/// See the [crate] docs for usage information.
#[proc_macro_attribute]
pub fn multiplatform_test(attr: TokenStream, body: TokenStream) -> TokenStream {
    let ts = multiplatform_test_impl(
        proc_macro2::TokenStream::from(attr),
        proc_macro2::TokenStream::from(body),
    );
    TokenStream::from(ts)
}

fn multiplatform_test_impl(
    attr: proc_macro2::TokenStream,
    body: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let mut attr = attr.into_iter();
    let mut platforms = Vec::<Platform>::new();

    while let Some(token) = attr.next() {
        let proc_macro2::TokenTree::Ident(i) = &token else {
            return quote_spanned! {token.span()=>
                compile_error!("malformed #[multiplatform_test] attribute; expected identifier.");
            };
        };
        let name = i.to_string();
        let Some(&platform) = Platform::ALL
            .iter()
            .find(|platform| name == platform.name())
        else {
            let msg = proc_macro2::Literal::string(&format!(
                "unknown platform {}; expected one of [{}]",
                name,
                Platform::ALL.map(Platform::name).join(", "),
            ));
            return quote_spanned! {token.span()=> compile_error!(#msg); };
        };
        platforms.push(platform);

        match &attr.next() {
            Some(proc_macro2::TokenTree::Punct(op)) if op.as_char() == ',' => {}
            Some(other) => {
                return quote_spanned! {other.span()=>
                    compile_error!("malformed `#[multiplatform_test]` attribute; expected `,`.");
                };
            }
            None => break,
        }
    }
    if platforms.is_empty() {
        platforms.extend(Platform::DEFAULT.iter());
    }

    let mut output = proc_macro2::TokenStream::new();
    let mut init_code = proc_macro2::TokenStream::new();

    for p in platforms {
        output.extend(p.make_attribute());
        init_code.extend(p.make_init_code());
    }

    if init_code.is_empty() {
        output.extend(body);
    } else {
        let mut body_head = body.into_iter().collect::<Vec<_>>();
        let Some(proc_macro2::TokenTree::Group(body_code)) = body_head.pop() else {
            panic!();
        };

        output.extend(body_head);
        output.extend(quote! {
            {
                { #init_code };
                #body_code
            }
        });
    }
    output
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_platforms() {
        let test_fn: proc_macro2::TokenStream = quote! { fn test() { } };
        let attrs = proc_macro2::TokenStream::new();
        let got: proc_macro2::TokenStream = multiplatform_test_impl(attrs, test_fn);
        let want = quote! {
            #[test]
            #[wasm_bindgen_test::wasm_bindgen_test]
            fn test() { }
        };

        assert_eq!(want.to_string(), got.to_string());
    }

    #[test]
    fn test_host_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { test };
        let got = multiplatform_test_impl(attrs, test_fn);
        let want = quote! {
            #[test]
            fn test() { }
        };

        assert_eq!(want.to_string(), got.to_string());
    }

    #[test]
    fn test_wasm_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { wasm };
        let got = multiplatform_test_impl(attrs, test_fn);
        let want = quote! {
            #[wasm_bindgen_test::wasm_bindgen_test]
            fn test() { }
        };

        assert_eq!(want.to_string(), got.to_string());
    }

    #[test]
    fn test_host_wasm_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { test, wasm };
        let got = multiplatform_test_impl(attrs, test_fn);
        let want = quote! {
            #[test]
            #[wasm_bindgen_test::wasm_bindgen_test]
            fn test() { }
        };

        assert_eq!(want.to_string(), got.to_string());
    }

    #[test]
    fn test_unknown_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { hello };
        let got = multiplatform_test_impl(attrs, test_fn);
        assert!(got.to_string().starts_with("compile_error !"));
    }

    #[test]
    fn test_invalid_attr_nocomma_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { wasm() };
        let got = multiplatform_test_impl(attrs, test_fn);
        assert!(got.to_string().starts_with("compile_error !"));
    }

    #[test]
    fn test_invalid_attr_noident_platform() {
        let test_fn = quote! { fn test() { } };
        let attrs = quote! { () };
        let got = multiplatform_test_impl(attrs, test_fn);
        assert!(got.to_string().starts_with("compile_error !"));
    }
}