lib.rs 1.64 KB
Newer Older
Raphaël Gomès's avatar
Raphaël Gomès committed
1
2
3
4
5
6
7
// 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;
8
9
10
11
12
13
14
15
16
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;

/// ```compile_fail
/// use micro_timer::timed;
///
/// #[timed]  // Can only be used on functions
/// struct Thing;
/// ```
Raphaël Gomès's avatar
Raphaël Gomès committed
17
18
19
#[proc_macro_attribute]
pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
    let ast = syn::parse(fn_ts.clone()).unwrap();
20
21
22
23
    let func = match parse_function(ast) {
        Ok(f) => f,
        Err(stream) => return stream,
    };
Raphaël Gomès's avatar
Raphaël Gomès committed
24
25
26
27
28
29
30
31
32
33
34
35
36

    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 block = quote! {
        {
            let timer = ::std::time::Instant::now();
            let mut inner = || { #inner_block };
            let ret = inner();

37
38
            crate::log::trace!(
                "Duration of `{}`: {:?}",
Raphaël Gomès's avatar
Raphaël Gomès committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
                #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()
}

53
fn parse_function(item: syn::Item) -> Result<syn::ItemFn, TokenStream> {
Raphaël Gomès's avatar
Raphaël Gomès committed
54
55
    match item {
        syn::Item::Fn(func) => Ok(func),
56
57
58
59
60
        i => Err(quote_spanned! {
            i.span() =>
            compile_error!("`#[timed]` can only be used on functions");
        }
        .into()),
Raphaël Gomès's avatar
Raphaël Gomès committed
61
62
    }
}