Debian Codegraph @

src/lib.rs

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