1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
//! This crate provides the `logfn` attribute macro for inserting logging code into your function.
//!
//! Currently we support 2 types of logging.
//!
//! - Pre logging
//! - Post logging
//!
//! And we have a plan to add `Time logging` and `Cound logging` type.
//!
//! Each `logfn` attribute injects a single logging code. You can put as many `logfn` as you want.
//!
//! ```
//! # use logfn::logfn;
//! # use std::num::ParseIntError;
//! #[logfn(Pre, Debug, "{fn} will be executed")]
//! #[logfn(Post, Debug, "{fn} is executed", if = "Result::is_ok")]
//! #[logfn(Post, Error, "Error while executing {fn}: {ret:?}", if = "Result::is_err")]
//! fn atoi(a: &str) -> Result<usize, ParseIntError> {
//!     usize::from_str_radix(a, 10)
//! }
//! ```
//!
//! The detail is documented below.
//!
//! # Pre logging
//!
//! The following attribute injects logging code **before** function is called.
//!
//! ```
//! use logfn::logfn;
//!
//! #[logfn(Pre, Info, "executing {fn}...")]
//! fn add(a: usize, b: usize) -> usize {
//!     a + b
//! }
//! ```
//!
//! The resulting code will looks like
//!
//! ```
//! fn add(a: usize, b: usize) -> usize {
//!     log::info!("executing add...");
//!
//!     {
//!         a + b
//!     }
//! }
//! ```
//!
//! # Post logging
//!
//! You also be able to inject logging code **after** function is called.
//!
//! ```
//! use logfn::logfn;
//!
//! #[logfn(Post, Info, "executed {fn}!")]
//! fn add(a: usize, b: usize) -> usize {
//!     a + b
//! }
//! ```
//!
//! The resulting code will looks like
//!
//! ```
//! fn add(a: usize, b: usize) -> usize {
//!     let ret = (move || {
//!         a + b
//!     })();
//!
//!     log::info!("executed add!");
//!
//!     ret
//! }
//! ```
//!
//! # Conditional logging
//!
//! You can configure the condition on which logging code is fired.
//! To do that, please add `if` argument with a path to the function which takes reference to
//! returned value and returns `true` when you want to fire the logging code.
//!
//! ## Note
//! Conditional logging is only supported in post logging for now.
//!
//! ```
//! use logfn::logfn;
//!
//! #[logfn(Post, Warn, "checked add is failed!!", if = "Option::is_none")]
//! fn checked_add(a: usize, b: usize) -> Option<usize> {
//!     a.checked_add(b)
//! }
//! ```
//!
//! # Message formatting
//!
//! We support below format patterns.
//!
//! - "{fn}" interpolates function name
//! - "{ret:?}" or "{ret}" interpolates returned value
//!
//! Note that "{ret}" pattern is only valid on Pre logging type.
//!
//! ```
//! # use std::num::ParseIntError;
//! use logfn::logfn;
//!
//! #[logfn(Post, Error, "Error while {fn} function: {ret:?}", if = "Result::is_err")]
//! fn atoi(s: &str) -> Result<usize, ParseIntError> {
//!     usize::from_str_radix(s, 10)
//! }
//! ```
//!
//! # Async function
//!
//! Async function is also supported.
//!
//! ```
//! use logfn::logfn;
//!
//! #[logfn(Post, Debug, "\"add_fut\" is executed")]
//! async fn add_fut(a: usize, b: usize) -> usize {
//!     a + b
//! }
//! ```
extern crate proc_macro;

mod arg;
mod config;

use proc_macro::TokenStream as StdTokenStream;
use proc_macro2::TokenStream;
use quote::quote;

use config::Config;

macro_rules! try_ok {
    ($x:expr) => {
        match $x {
            Ok(ok) => ok,
            Err(e) => return e.to_compile_error().into(),
        }
    };
}

#[proc_macro_attribute]
pub fn logfn(input_args: StdTokenStream, input: StdTokenStream) -> StdTokenStream {
    // parse config
    let input_args = syn::parse_macro_input!(input_args as syn::AttributeArgs);
    let args = try_ok!(arg::from_input_vec(input_args));
    let config = try_ok!(config::from_args(args));

    // parse input
    let input = syn::parse_macro_input!(input as syn::ItemFn);

    produce_logfn(config, input).into()
}

fn produce_logfn(config: Config, input: syn::ItemFn) -> TokenStream {
    match config.typ {
        arg::TypeArg::Pre => produce_logfn_pre(config, input),
        arg::TypeArg::Post => produce_logfn_post(config, input),
    }
}

// This produces
//
// ```rust
// pub fn add(a: usize, b: usize) -> usize {
//     log::info!();
//
//     {
//         a + b
//     }
// }
// ```
fn produce_logfn_pre(config: Config, input: syn::ItemFn) -> TokenStream {
    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;

    let log_stmt = produce_log_stmt(&config, &input);

    quote! {
        #(#attrs)*
        #vis #sig {
            #log_stmt

            #block
        }
    }
}

// This produces
//
// ```rust
// pub fn add(a: usize, b: usize) -> usize {
//     fn __logfn_inner(a: usize, b: usize) -> usize {
//         a + b
//     }
//     let ret = __logfn_inner();
//
//     log::log!(log::Level::Info, "hoge");
//
//     ret
// }
// ```
fn produce_logfn_post(config: Config, input: syn::ItemFn) -> TokenStream {
    let attrs = &input.attrs;
    let vis = &input.vis;
    let sig = &input.sig;

    let closure_call = produce_closure_call(&input);

    let log_stmt = produce_log_stmt(&config, &input);

    let cond_expr = config
        .cond
        .map(|cond| {
            let path = cond.path;
            quote! { #path(&ret) }
        })
        .unwrap_or(quote! { true });

    quote! {
        #(#attrs)*
        #vis #sig {
            let ret = #closure_call;

            if #cond_expr {
                #log_stmt
            }

            ret
        }
    }
}

fn produce_closure_call(input: &syn::ItemFn) -> TokenStream {
    let block = &input.block;

    if input.sig.asyncness.is_some() {
        quote! {
            (move || async move #block)().await
        }
    } else {
        quote! {
            (move || #block)()
        }
    }
}

fn produce_log_stmt(config: &Config, input: &syn::ItemFn) -> TokenStream {
    let log_level = config.level.ident();
    let log_msg = &config.msg.msg;

    let mut args = vec![];
    if log_msg.contains("{ret:?}") || log_msg.contains("{ret}") {
        args.push(quote! { ret = ret });
    }
    if log_msg.contains("{fn}") {
        let fn_name = input.sig.ident.clone().to_string();
        args.push(quote! { fn = #fn_name });
    }

    quote! {
        log::log!(log::Level::#log_level, #log_msg #(, #args)*);
    }
}