optick_attr/
lib.rs

1extern crate proc_macro;
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::{ItemFn, parse_macro_input, parse_quote};
5
6/// Instrument selected function
7/// 
8/// Example:
9/// #[optick_attr::profile]
10/// fn calc() {
11///	    // Do some stuff
12///}
13#[proc_macro_attribute]
14#[cfg(all(feature = "enable"))]
15pub fn profile(_attr: TokenStream, item: TokenStream) -> TokenStream {
16    let mut function = parse_macro_input!(item as ItemFn);
17
18    let body = &function.block;
19    let new_body: syn::Block = parse_quote! {
20        {
21            optick::event!();
22            #body
23        }
24    };
25
26    function.block = Box::new(new_body);
27
28    (quote! {
29        #function
30    })
31    .into()
32}
33
34/// Generate profiling capture for the selected function
35/// Saves capture to {working_dir}/capture_name(date-time).opt
36/// Note: You could use full path for the name (e.g. "D:/captures/game")
37/// 
38/// Example:
39/// #[optick_attr::capture("capture_name")]
40/// pub fn main() {
41///     calc();
42/// }
43#[proc_macro_attribute]
44#[cfg(all(feature = "enable"))]
45pub fn capture(attr: TokenStream, item: TokenStream) -> TokenStream {
46    let path_arg = attr.to_string();
47    let path_length = path_arg.len();
48    let path = if path_length < 2 {
49        "optick_capture"
50    } else {
51        &path_arg[1..path_length-1]
52    };
53    let mut function = parse_macro_input!(item as ItemFn);
54    let body = &function.block;
55    let new_body: syn::Block = parse_quote! {
56        {
57            optick::start_capture();
58            let result = #body;
59            optick::stop_capture(#path);
60            result
61        }
62    };
63
64    function.block = Box::new(new_body);
65
66    (quote! {
67        #function
68    })
69    .into()
70}