Debian Codegraph @

src/lib.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use darling::FromMeta;
2 use quote::quote;
3 use syn::{parse_macro_input, ReturnType};
4
5 macro_rules! make_darling_error {
6 ($($arg:tt)*) => {
7 Err(darling::Error::custom(format!($($arg)*)))
8 };
9 }
10
11 macro_rules! make_compile_error {
12 ($($arg:tt)*) => {
13 quote! { compile_error!($($arg)*) }.into()
14 };
15 }
16
17 /// Determines when to collect execution time information.
18 #[derive(FromMeta)]
19 enum When {
20 /// Always collect timing information.
21 Always,
22 /// Only collect timing information if `cfg!(debug_assertions)` evaluates to `true`.
23 Debug,
24 }
25
26 /// By default we always collect timing information.
27 impl Default for When {
28 fn default() -> Self {
29 Self::Always
30 }
31 }
32
33 impl When {
34 /// Parse the [`When`] argument from a given string literal.
35 fn from_lit(literal: syn::LitStr) -> Result<Self, darling::Error> {
36 match literal.value().as_str() {
37 "always" => Ok(Self::Always),
38 "debug" => Ok(Self::Debug),
39 unsupported => make_darling_error!(
40 "Unsupported value for `when` attribute: {unsupported}. Use one of: always, debug"
41 ),
42 }
43 }
44 }
45
46 /// Determines how to report the captured execution time information.
47 ///
48 /// It will print both a start and done message.
49 /// The format of the start message is: "Starting: YOUR_MESSAGE_HERE"
50 /// The format of the done message is: "YOUR_MESSAGE_HERE: Done in ELAPSED_TIME"
51 ///
52 /// The `ELAPSED_TIME` is the debug format of [`std::time::Duration`].
53 #[derive(FromMeta)]
54 enum Reporting {
55 /// Use a simple `println!` statement to print the information to the `stdout`.
56 Println,
57 /// Use the [log](https://crates.io/crates/log) crate to print the information using the
58 /// provided `info!` macro.
59 #[cfg(feature = "log")]
60 Log,
61 }
62
63 /// By default we use the simple `println!` to write the reporting info to the `stdout`.
64 impl Default for Reporting {
65 #[cfg(not(feature = "log"))]
66 fn default() -> Self {
67 Self::Println
68 }
69
70 #[cfg(feature = "log")]
71 fn default() -> Self {
72 Self::Log
73 }
74 }
75
76 impl Reporting {
77 /// Parse the [`Reporting`] argument from a given string literal.
78 fn from_lit(literal: syn::LitStr) -> Result<Self, darling::Error> {
79 match literal.value().as_str() {
80 "println" => Ok(Self::Println),
81 #[cfg(feature = "log")]
82 "log" => Ok(Self::Log),
83 unsupported => make_darling_error!("Unsupported value for `reporting` attribute: {unsupported}. Use one of: println, (only with log feature) log")
84 }
85 }
86 }
87
88 #[cfg(feature = "log")]
89 mod log_level {
90 use super::*;
91 use std::str::FromStr;
92
93 pub struct Level(pub log::Level);
94
95 impl FromMeta for Level {}
96
97 impl Default for Level {
98 fn default() -> Self {
99 Self(log::Level::Info)
100 }
101 }
102
103 impl Level {
104 pub fn from_lit(literal: syn::LitStr) -> Result<Self, darling::Error> {
105 Ok(Self(log::Level::from_str(&literal.value()).map_err(|_| {
106 darling::Error::custom(format!(
107 "Unsupported value for `level` attribute: {unsupported}. Use one of: trace, debug, info, warn, error",
108 unsupported = literal.value()
109 ))
110 })?))
111 }
112 }
113 }
114
115 #[derive(FromMeta)]
116 struct FunTimeArgs {
117 #[darling(default)]
118 message: Option<String>,
119 /// Determines when we should perform the timing.
120 #[darling(default)]
121 #[darling(and_then = "When::from_lit")]
122 when: When,
123 /// Determines whether the elapsed time should be returned or that we log it immediately
124 /// to stdout.
125 #[darling(default)]
126 give_back: bool,
127 #[darling(default)]
128 #[darling(and_then = "Reporting::from_lit")]
129 reporting: Reporting,
130
131 #[cfg(feature = "log")]
132 #[darling(default)]
133 #[darling(and_then = "log_level::Level::from_lit")]
134 level: log_level::Level,
135 }
136
137 /// Measure the execution times of the function under the attribute.
138 ///
139 /// It does this by wrapping the function in a new block surrounded by a [`std::time::Instant::now()`]
140 /// call and a [`std::time::Instant::elapsed()`] call. It then either logs the duration directly or
141 /// returns it with the original functions return value, depending on how you configured this
142 /// attribute.
143 ///
144 /// # Attributes
145 ///
146 /// ## when
147 ///
148 /// The `when` attribute can be used to configure when the timing information is collected. For
149 /// example, with `"always"` the timing information is always collected, but with `"debug"` the
150 /// timing information is only collected if the `cfg!(debug_assertions)` statement evaluates to
151 /// `true`.
152 ///
153 /// ## give_back
154 ///
155 /// The `give_back` attribute can be used to switch the macro from printing mode to returning the
156 /// captured elapsed time together with the original return value of the function. It will modify
157 /// the original return value to be a tuple, where the first value is the original return value
158 /// and the second value is the elapsed time as a [`std::time::Duration`] struct.
159 ///
160 /// ## message
161 ///
162 /// The `message` attribute allows you to set a message that will be displayed in the case you
163 /// chose to let the macro report the elapsed time directly. This message will be shown both in
164 /// the start and done messages.
165 ///
166 /// ## reporting
167 ///
168 /// The `reporting` attribute determines how the message and elapsed time will be displayed
169 /// directly when you have chosen not to let the macro return the elapsed time to you. By default
170 /// it uses a simple `println!` statement, but with the optional `log` feature it will use the
171 /// [log](https://crates.io/crates/log) crate to log it using the `info!` macro.
172 ///
173 /// # Example
174 ///
175 /// ```
176 /// // Replace this in your code with `use fun_time::fun_time;`
177 /// use fun_time_derive::fun_time;
178 ///
179 /// #[fun_time(give_back)]
180 /// fn function_with_heavy_calculations(some_data: Vec<i32>) -> bool {
181 /// // Big brain calculations...
182 /// true
183 /// }
184 ///
185 /// fn main() {
186 /// let my_data = vec![1, 2, 3];
187 ///
188 /// // Run the function and receive timing information
189 /// let (my_original_return_value, how_long_did_it_take) = function_with_heavy_calculations(my_data);
190 /// }
191 /// ```
192 #[proc_macro_attribute]
193 pub fn fun_time(
194 args: proc_macro::TokenStream,
195 item: proc_macro::TokenStream,
196 ) -> proc_macro::TokenStream {
197 let raw_args: syn::AttributeArgs = parse_macro_input!(args as syn::AttributeArgs);
198 let args: FunTimeArgs = match FunTimeArgs::from_list(&raw_args) {
199 Ok(args) => args,
200 Err(error) => return error.write_errors().into(),
201 };
202
203 if args.message.is_some() && args.give_back {
204 return make_compile_error!(
205 "the `message` and `give_back` attributes can not be used together!"
206 );
207 }
208
209 let item_fn: syn::ItemFn = parse_macro_input!(item as syn::ItemFn);
210
211 // Check if we should time the function
212 match args.when {
213 When::Debug if args.give_back => return make_compile_error!("the `give_back` and `when` attribute with `\"debug\"` can not be used together! It would result in different return types"),
214 When::Debug if !cfg!(debug_assertions) => return quote! { #item_fn }.into(),
215 _ => {} // No restrictions, go ahead!
216 }
217
218 let visibility = item_fn.vis;
219 let signature = item_fn.sig.clone();
220 let output = item_fn.sig.output;
221
222 // Contains the original logic of the function
223 let block = item_fn.block;
224
225 // Create wrapped function block
226 let wrapped_block = quote! {
227 let super_secret_variable_that_does_not_clash_start = std::time::Instant::now();
228
229 // Immediately invoked closure so a `return` statement in the original function does not
230 // break the logging. This also works with self-mutating structs.
231 // We also put the original return type as return type for the closure otherwise things like
232 // -> Box<dyn Trait> can not be correctly inferred by the compiler.
233 let return_value = (|| #output #block)();
234
235 let elapsed = super_secret_variable_that_does_not_clash_start.elapsed();
236 };
237
238 // Create tokens for the `log` call if it is enabled
239 #[cfg(feature = "log")]
240 let log_tokens = match args.level.0 {
241 log::Level::Error => quote! { log::error! },
242 log::Level::Warn => quote! { log::warn! },
243 log::Level::Info => quote! { log::info! },
244 log::Level::Debug => quote! { log::debug! },
245 log::Level::Trace => quote! { log::trace! },
246 };
247
248 // Depending on our `give_back` attibute we either return the elapsed time or not
249 let tokens = if args.give_back {
250 // Deconstruct the signature because we need to edit the return type
251 let syn::Signature {
252 ident,
253 generics,
254 inputs,
255 output,
256 ..
257 } = signature;
258 let where_clause = &generics.where_clause;
259
260 // Modify our output type to also return a std::time::Duration (our elapsed time)
261 // In case of an empty return type we can simply return the std::time::Duration, otherwise
262 // we have to wrap it in a tuple.
263 let output_with_duration = match output {
264 ReturnType::Default => syn::parse_str::<ReturnType>("-> std::time::Duration").unwrap(),
265 ReturnType::Type(_, ty) => syn::parse_str::<ReturnType>(&format!(
266 "-> ({}, std::time::Duration)",
267 quote! { #ty }
268 ))
269 .unwrap(),
270 };
271
272 quote! {
273 #visibility fn #ident #generics (#inputs) #output_with_duration #where_clause {
274 #wrapped_block
275
276 (return_value, elapsed)
277 }
278 }
279 } else {
280 let message = args.message.unwrap_or_default();
281
282 // Store the message at the top of the function because if the function were to take
283 // ownership of the argument it would be gone by the time we want to print the done message.
284 let message_statement = quote! {
285 let super_secret_variable_that_does_not_clash_message = format!(#message);
286 };
287
288 let starting_statement = match args.reporting {
289 Reporting::Println => quote! {
290 println!("{}", super_secret_variable_that_does_not_clash_message);
291 },
292 #[cfg(feature = "log")]
293 Reporting::Log => quote! {
294 #log_tokens("{}", super_secret_variable_that_does_not_clash_message);
295 },
296 };
297
298 let reporting_statement = match args.reporting {
299 Reporting::Println => quote! {
300 println!("{}: Done in {:.2?}", super_secret_variable_that_does_not_clash_message, elapsed);
301 },
302 #[cfg(feature = "log")]
303 Reporting::Log => quote! {
304 #log_tokens("{}: Done in {:.2?}", super_secret_variable_that_does_not_clash_message, elapsed);
305 },
306 };
307
308 quote! {
309 #visibility #signature {
310 #message_statement
311 #starting_statement
312
313 #wrapped_block
314
315 #reporting_statement
316
317 return_value
318 }
319 }
320 };
321
322 tokens.into()
323 }