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

Add better error message when using `timed` on something else than a function

parent 5138d01934e5
......@@ -5,14 +5,22 @@
/// `extern crate` Required even for 2018 edition
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
type StaticResult<T> = ::std::result::Result<T, &'static str>;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
/// ```compile_fail
/// use micro_timer::timed;
///
/// #[timed] // Can only be used on functions
/// struct Thing;
/// ```
#[proc_macro_attribute]
pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let ast = syn::parse(fn_ts.clone()).unwrap();
let func = parse_function(ast).unwrap();
let func = match parse_function(ast) {
Ok(f) => f,
Err(stream) => return stream,
};
let mut outer = func.clone();
outer.sig.ident = func.sig.ident.to_owned();
......@@ -42,9 +50,13 @@ pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
(quote! {#outer}).into()
}
fn parse_function(item: syn::Item) -> StaticResult<syn::ItemFn> {
fn parse_function(item: syn::Item) -> Result<syn::ItemFn, TokenStream> {
match item {
syn::Item::Fn(func) => Ok(func),
_ => Err("`time_it` attribute can only be used on functions"),
i => Err(quote_spanned! {
i.span() =>
compile_error!("`#[timed]` can only be used on functions");
}
.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