Commit be3cf29e authored by Raphaël Gomès's avatar Raphaël Gomès
Browse files

Move to `proc_macro2` to be able to unit-test the macro and need fewer `into()`

parent 431dabc3a3cb
......@@ -18,6 +18,7 @@ name = "micro-timer"
version = "0.1.1"
dependencies = [
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 1.0.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
......
......@@ -15,6 +15,7 @@ proc-macro = true
[dependencies]
syn = {version = "1.0.16", features = ["full", "extra-traits"]}
quote = "1.0.2"
proc-macro2 = "1.0.9"
[dev-dependencies]
log = "0.4.8"
\ No newline at end of file
......@@ -4,10 +4,12 @@
/// `extern crate` Required even for 2018 edition
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
/// Logs the time elapsed for the body of the target function for each call.
///
/// ```compile_fail
/// use micro_timer::timed;
///
......@@ -15,8 +17,16 @@ use syn::spanned::Spanned;
/// struct Thing;
/// ```
#[proc_macro_attribute]
pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let ast = syn::parse(fn_ts.clone()).unwrap();
pub fn timed(
attrs: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
inner_timed(attrs.into(), item.into()).into()
}
/// This is the unit-testable version using `proc_macro2`
fn inner_timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let ast = syn::parse2(fn_ts.clone()).unwrap();
let func = match parse_function(ast) {
Ok(f) => f,
Err(stream) => return stream,
......@@ -77,11 +87,10 @@ pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
ret
}
};
// `quote` works with `proc_macro2::TokenStream`, not
// `proc_macro::TokenStream`... thankfully you can just `.into()` them
outer.block = syn::parse(block.into()).unwrap();
(quote! {#outer}).into()
outer.block = syn::parse2(block).unwrap();
(quote! {#outer})
}
fn parse_function(item: syn::Item) -> Result<syn::ItemFn, TokenStream> {
......@@ -91,7 +100,6 @@ fn parse_function(item: syn::Item) -> Result<syn::ItemFn, TokenStream> {
i.span()=>
compile_error!("`#[timed]` can only be used on functions");
#i
}
.into()),
}),
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment