shared_tokio_runtime_macros/
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
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, Item, Stmt};

#[proc_macro_attribute]
pub fn runtime(_metadata: TokenStream, input: TokenStream) -> TokenStream {
    let input: Item = match parse_macro_input!(input as Item) {
        Item::Fn(mut fn_item) => {
            fn_item.sig.asyncness = None;
            let old_block = fn_item.block.clone();
            let new_block_stmt: Stmt = parse_quote! {
                shared_tokio_runtime::rt().block_on(async {
                    #old_block
                })
            };
            fn_item.block.stmts = vec![new_block_stmt];
            Item::Fn(fn_item)
        },
        _ => {
            panic!("The `runtime` macro attribute is only valid when called on a fn.")
        }
    };
    TokenStream::from(quote! (#input))
}