Files
tokio/tokio-macros/src/lib.rs
T

88 lines
2.1 KiB
Rust
Raw Normal View History

2019-05-14 10:27:36 -07:00
#![deny(missing_debug_implementations, unreachable_pub, rust_2018_idioms)]
#![cfg_attr(test, deny(warnings))]
#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))]
//! Macros for use with Tokio
2019-04-25 19:22:32 -07:00
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
/// Define the program entry point
///
/// # Examples
///
/// ```
/// #[tokio::main]
/// async fn main() {
/// println!("Hello from Tokio!");
2019-04-25 19:22:32 -07:00
/// }
/// ```
2019-04-25 19:22:32 -07:00
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
2019-04-25 19:22:32 -07:00
pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let ret = &input.decl.output;
let name = &input.ident;
let body = &input.block;
if input.asyncness.is_none() {
let tokens = quote_spanned! { input.span() =>
compile_error!("the async keyword is missing from the function declaration");
};
return TokenStream::from(tokens);
}
let result = quote! {
fn #name() #ret {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { #body })
2019-04-25 19:22:32 -07:00
}
};
result.into()
}
/// Define a Tokio aware unit test
///
/// # Examples
///
/// ```ignore
2019-04-25 19:22:32 -07:00
/// #[tokio::test]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
#[proc_macro_attribute]
pub fn test(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let ret = &input.decl.output;
let name = &input.ident;
let body = &input.block;
let attrs = &input.attrs;
2019-04-25 19:22:32 -07:00
if input.asyncness.is_none() {
let tokens = quote_spanned! { input.span() =>
compile_error!("the async keyword is missing from the function declaration");
};
return TokenStream::from(tokens);
}
let result = quote! {
#[test]
#(#attrs)*
2019-04-25 19:22:32 -07:00
fn #name() #ret {
let mut rt = tokio::runtime::current_thread::Runtime::new().unwrap();
2019-06-27 02:41:36 +08:00
rt.block_on(async { #body })
2019-04-25 19:22:32 -07:00
}
};
result.into()
}