flogging_macros/src/logger.rs

Lines

100.00 %

Functions

100.00 %

Regions

100.00 %

LineCountSource
1
//
2
// File Name:    logger.rs
3
// Project Name: flogging
4
//
5
// Copyright (C) 2025 Bradley Willcott
6
//
7
// SPDX-License-Identifier: GPL-3.0-or-later
8
//
9
// This library (crate) is free software: you can redistribute it and/or modify
10
// it under the terms of the GNU General Public License as published by
11
// the Free Software Foundation, either version 3 of the License, or
12
// (at your option) any later version.
13
//
14
// This library (crate) is distributed in the hope that it will be useful,
15
// but WITHOUT ANY WARRANTY; without even the implied warranty of
16
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
// GNU General Public License for more details.
18
//
19
// You should have received a copy of the GNU General Public License
20
// along with this library (crate).  If not, see <https://www.gnu.org/licenses/>.
21
//
22
23
//!
24
//! # Logger Macro Impl
25
//!
26
27
use proc_macro::TokenStream;
28
use quote::quote;
29
use syn::{ItemFn, parse_macro_input};
30
3111
pub(crate) fn logger_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
32
    // println!("attr: (is_empty: {}) {attr}", attr.to_string().is_empty());
33
34
    // Parse the input as `ItemFn` which is a type provided
35
    // by `syn` to represent a function.
3611
    let input = parse_macro_input!(item as ItemFn);
37
38
    let ItemFn {
39
        // The function signature
4011
        sig,
41
        // The visibility specifier of this function
4211
        vis,
43
        // The function block or body
4411
        block,
45
        // Other attributes applied to this function
4611
        attrs,
4711
    } = input;
48
49
    // Extract statements in the body of the functions
5011
    let statements = block.stmts;
51
52
    // Store the function identifier for logging
5311
    let function_identifier = if attr.to_string().is_empty() {
5410
        sig.ident.clone().to_string()
55
    } else {
561
        attr.to_string()
57
    };
58
59
    // Reconstruct the function as output using parsed input
6011
    quote!(
61
        // Reapply all the other attributes on this function.
62
        // The compiler doesn't include the macro we are
63
        // currently working in this list.
64
        #(#attrs)*
65
        // Reconstruct the function declaration
66
        #vis #sig {
67
            // At the beginning of the function, borrow a reference to
68
            // module level static logger.
69
            let __binding = LOGGER;
70
            let mut __log = __binding.borrow_mut();
71
            __log.set_fn_name(#function_identifier);
72
73
            #(#statements)*
74
        }
75
    )
7611
    .into()
7711
}