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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![recursion_limit = "512"]

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{quote, quote_spanned};
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;

/// Enables an async main function.
///
/// # Examples
///
/// ## Dynamic threads
///
/// By default, this spawns as many threads as is in the `SMOL_THREADS` environment variable, or 1
/// if it is not specified.
///
/// ```ignore
/// #[smol_potat::main]
/// async fn main() -> std::io::Result<()> {
///     Ok(())
/// }
/// ```
///
/// ## Automatic Threadpool
///
/// Alternatively, `smol_potat::main` can used to automatically
/// set the number of threads by adding the `auto` feature (off
/// by default).
///
/// ```ignore
/// #[smol_potat::main] // with 'auto' feature enabled
/// async fn main() -> std::io::Result<()> {
///     Ok(())
/// }
/// ```
///
/// ## Manually Configure Threads
///
/// To manually set the number of threads, add this to the attribute:
///
/// ```ignore
/// #[smol_potat::main(threads=3)]
/// async fn main() -> std::io::Result<()> {
///     Ok(())
/// }
/// ```
///
/// ## Set the crate root
///
/// By default `smol-potat` will use `::smol_potat` as its crate root, but you can override this
/// with the `crate` option:
///
/// ```ignore
/// use smol_potat as other_smol_potat;
///
/// #[smol_potat::main(crate = "other_smol_potat")]
/// async fn main() -> std::io::Result<()> {
///     Ok(())
/// }
/// ```
#[proc_macro_attribute]
pub fn main(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let opts = syn::parse_macro_input!(attr as Opts);

    let ret = &input.sig.output;
    let name = &input.sig.ident;
    let body = &input.block;
    let attrs = &input.attrs;

    let crate_root = opts.crate_root;

    if name != "main" {
        return TokenStream::from(quote_spanned! { name.span() =>
            compile_error!("only the main function can be tagged with #[smol::main]"),
        });
    }

    if !input.sig.inputs.is_empty() {
        return TokenStream::from(quote_spanned! { input.sig.paren_token.span =>
            compile_error!("the main function cannot take parameters"),
        });
    }

    if input.sig.asyncness.is_none() {
        return TokenStream::from(quote_spanned! { input.span() =>
            compile_error!("the async keyword is missing from the function declaration"),
        });
    }

    let threads = match opts.threads {
        Some((num, span)) => {
            let num = num.to_string();
            Some(quote_spanned!(span=> #num))
        }
        #[cfg(feature = "auto")]
        None => Some(quote! {
            #crate_root::std::string::ToString::to_string(
                &#crate_root::std::cmp::max(#crate_root::num_cpus::get(), 1)
            )
        }),
        #[cfg(not(feature = "auto"))]
        None => None,
    };

    let set_threads = threads.map(|threads| {
        quote! {
            #crate_root::std::env::set_var(
                "SMOL_THREADS",
                #threads,
            );
        }
    });

    let result = quote! {
        fn main() #ret {
            #(#attrs)*
            async fn main() #ret {
                #body
            }

            #set_threads

            #crate_root::async_io::block_on(main())
        }
    };

    result.into()
}

/// Enables an async test function.
///
/// # Examples
///
/// ```ignore
/// #[smol_potat::test]
/// async fn my_test() -> std::io::Result<()> {
///     assert_eq!(2 * 2, 4);
///     Ok(())
/// }
/// ```
#[proc_macro_attribute]
pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let opts = syn::parse_macro_input!(attr as Opts);

    let ret = &input.sig.output;
    let name = &input.sig.ident;
    let body = &input.block;
    let attrs = &input.attrs;

    let crate_root = opts.crate_root;

    if let Some((_, span)) = opts.threads {
        return TokenStream::from(quote_spanned! { span=>
            compile_error!("tests cannot have threads attribute"),
        });
    }
    if !input.sig.inputs.is_empty() {
        return TokenStream::from(quote_spanned! { input.span() =>
            compile_error!("tests cannot take parameters"),
        });
    }
    if input.sig.asyncness.is_none() {
        return TokenStream::from(quote_spanned! { input.span() =>
            compile_error!("the async keyword is missing from the function declaration"),
        });
    }

    let result = quote! {
        #[test]
        #(#attrs)*
        fn #name() #ret {
            #crate_root::async_io::block_on(async { #body })
        }
    };

    result.into()
}

/// Enables an async benchmark function.
///
/// # Examples
///
/// ```ignore
/// #![feature(test)]
/// extern crate test;
///
/// #[smol_potat::bench]
/// async fn bench() {
///     println!("hello world");
/// }
/// ```
#[proc_macro_attribute]
pub fn bench(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::ItemFn);
    let opts = syn::parse_macro_input!(attr as Opts);

    let ret = &input.sig.output;
    let name = &input.sig.ident;
    let body = &input.block;
    let attrs = &input.attrs;

    let crate_root = opts.crate_root;

    if let Some((_, span)) = opts.threads {
        return TokenStream::from(quote_spanned! { span=>
            compile_error!("benchmarks cannot have threads attribute"),
        });
    }
    if !input.sig.inputs.is_empty() {
        return TokenStream::from(quote_spanned! { input.span() =>
            compile_error!("benchmarks cannot take parameters"),
        });
    }
    if input.sig.asyncness.is_none() {
        return TokenStream::from(quote_spanned! { input.span() =>
            compile_error!("the async keyword is missing from the function declaration"),
        });
    }

    let result = quote! {
        #[bench]
        #(#attrs)*
        fn #name(b: &mut ::test::Bencher) #ret {
            let _ = b.iter(|| {
                #crate_root::async_io::block_on(async {
                    #body
                })
            });
        }
    };

    result.into()
}

struct Opts {
    crate_root: syn::Path,
    threads: Option<(u32, Span)>,
}

impl Parse for Opts {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let mut crate_root = None;
        let mut threads = None;

        loop {
            if input.is_empty() {
                break;
            }

            let name_value: syn::MetaNameValue = input.parse()?;
            let ident = match name_value.path.get_ident() {
                Some(ident) => ident,
                None => {
                    return Err(syn::Error::new_spanned(
                        name_value.path,
                        "Must be a single ident",
                    ))
                }
            };
            match &*ident.to_string().to_lowercase() {
                "threads" => match &name_value.lit {
                    syn::Lit::Int(expr) => {
                        if threads.is_some() {
                            return Err(syn::Error::new_spanned(
                                name_value,
                                "multiple threads argments",
                            ));
                        }

                        let num = expr.base10_parse::<std::num::NonZeroU32>()?;
                        threads = Some((num.get(), expr.span()));
                    }
                    _ => {
                        return Err(syn::Error::new_spanned(
                            name_value,
                            "threads argument must be an integer",
                        ))
                    }
                },
                "crate" => match &name_value.lit {
                    syn::Lit::Str(path) => {
                        if crate_root.is_some() {
                            return Err(syn::Error::new_spanned(
                                name_value,
                                "multiple crate arguments",
                            ));
                        }

                        crate_root = Some(path.parse()?);
                    }
                    _ => {
                        return Err(syn::Error::new_spanned(
                            name_value,
                            "crate argument must be a string",
                        ))
                    }
                },
                name => {
                    return Err(syn::Error::new_spanned(
                        name,
                        "unknown attribute {}, expected `threads` or `crate`",
                    ));
                }
            }

            input.parse::<Option<syn::Token![,]>>()?;
        }

        Ok(Self {
            crate_root: crate_root.unwrap_or_else(|| syn::parse2(quote!(::smol_potat)).unwrap()),
            threads,
        })
    }
}