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
// micro-timer
//
// Copyright 2020, Raphaël Gomès <rgomes@octobus.net>

/// `extern crate` Required even for 2018 edition
extern crate proc_macro;
use proc_macro::TokenStream;
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 = match parse_function(ast) {
        Ok(f) => f,
        Err(stream) => return stream,
    };

    let mut outer = func.clone();
    outer.sig.ident = func.sig.ident.to_owned();
    let original_func_name = func.sig.ident.to_string();

    let inner_block = &func.block;
    let span = outer.sig.ident.span();

    let block = quote_spanned! {
        span=>
        {
            let timer = ::std::time::Instant::now();
            let mut inner = || { #inner_block };
            let ret = inner();

            crate::log::trace!(
                "Duration of `{}`: {:?}",
                #original_func_name,
                timer.elapsed()
            );

            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()
}

fn parse_function(item: syn::Item) -> Result<syn::ItemFn, TokenStream> {
    match item {
        syn::Item::Fn(func) => Ok(func),
        i => Err(quote_spanned! {
            i.span()=>
            compile_error!("`#[timed]` can only be used on functions");
            #i
        }
        .into()),
    }
}