embedded_profiling_proc_macros/
lib.rs

1//! Procedural macros for the [`embedded-profiling`] crate. Meant to only be accessed
2//! via that crate. See [`embedded-profiling`] for full documentation.
3//!
4//! [`embedded-profiling`]: https://docs.rs/embedded-profiling/
5extern crate proc_macro;
6use proc_macro::TokenStream;
7
8use quote::quote;
9use syn::{parse_macro_input, parse_quote, ItemFn};
10
11#[proc_macro_attribute]
12/// profiles the annotated function using `embedded_profiling`.
13/// ```
14/// #[embedded_profiling::profile_function]
15/// fn my_long_running_function() {
16///     println!("Hello, world!");
17/// }
18/// // Prints:
19/// // Hello, world!
20/// // <EPSS my_long_running_function: xx us>
21/// ```
22pub fn profile_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
23    let mut function = parse_macro_input!(item as ItemFn);
24    let instrumented_function_name = function.sig.ident.to_string();
25
26    let body = &function.block;
27    let new_body: syn::Block = parse_quote! {
28        {
29            let start = embedded_profiling::start_snapshot();
30            #body
31            if let Some(dur) = embedded_profiling::end_snapshot(start, #instrumented_function_name) {
32                embedded_profiling::log_snapshot(&dur);
33            }
34        }
35    };
36
37    function.block = Box::new(new_body);
38
39    (quote! {
40        #function
41    })
42    .into()
43}