cu29-log-derive 0.15.0

This is part of the text logging macros Copper. It cannot be used independently from the copper project.
Documentation
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
extern crate proc_macro;

use cu29_intern_strs::intern_string;
use cu29_log::CuLogLevel;
use proc_macro::TokenStream;
#[cfg(feature = "textlogs")]
use proc_macro_crate::{FoundCrate, crate_name};
#[cfg(feature = "textlogs")]
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
#[allow(unused)]
use syn::Token;
use syn::parse::Parser;
#[cfg(any(feature = "textlogs", debug_assertions))]
use syn::spanned::Spanned;
use syn::{Expr, ExprLit, Lit};

/// Create reference of unused_variables to avoid warnings
/// ex: let _ = &tmp;
#[allow(unused)]
fn reference_unused_variables(input: TokenStream) -> TokenStream {
    // Attempt to parse the expressions to "use" them.
    // This ensures variables passed to the macro are considered used by the compiler.
    let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated;
    if let Ok(exprs) = parser.parse(input.clone()) {
        let mut var_usages = Vec::new();
        // Skip the first expression, which is assumed to be the format string literal.
        // We only care about "using" the subsequent variable arguments.
        for expr in exprs.iter().skip(1) {
            match expr {
                // If the argument is an assignment (e.g., `foo = bar`),
                // we need to ensure `bar` (the right-hand side) is "used".
                syn::Expr::Assign(assign_expr) => {
                    let value_expr = &assign_expr.right;
                    var_usages.push(quote::quote! { let _ = &#value_expr; });
                }
                // Otherwise, for any other expression, ensure it's "used".
                _ => {
                    var_usages.push(quote::quote! { let _ = &#expr; });
                }
            }
        }
        // Return a block that contains these dummy "usages".
        // If only a format string was passed, var_usages will be empty,
        // resulting in an empty block `{}`, which is fine.
        return quote::quote! { { #(#var_usages;)* } }.into();
    }

    // Fallback: if parsing fails for some reason, return an empty TokenStream.
    // This might still lead to warnings if parsing failed but is better than panicking.
    TokenStream::new()
}

/// Create a log entry at the specified log level.
///
/// This is the internal macro implementation used by all the logging macros.
/// Users should use the public-facing macros: `debug!`, `info!`, `warning!`, `error!`, or `critical!`.
#[allow(unused)]
fn create_log_entry(input: TokenStream, level: CuLogLevel) -> TokenStream {
    use quote::quote;
    use syn::{Expr, ExprAssign, ExprLit, Lit, Token};

    let parser = syn::punctuated::Punctuated::<Expr, Token![,]>::parse_terminated;
    let exprs = match parser.parse(input) {
        Ok(exprs) => exprs,
        Err(err) => return err.to_compile_error().into(),
    };
    let mut exprs_iter = exprs.iter();

    #[cfg(not(feature = "std"))]
    const STD: bool = false;
    #[cfg(feature = "std")]
    const STD: bool = true;

    let msg_expr = match exprs_iter.next() {
        Some(expr) => expr,
        None => {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                "Expected at least one expression",
            )
            .to_compile_error()
            .into();
        }
    };
    let (index, msg_str) = if let Expr::Lit(ExprLit {
        lit: Lit::Str(msg), ..
    }) = msg_expr
    {
        let s = msg.value();
        let index = match intern_string(&s) {
            Some(index) => index,
            None => {
                return syn::Error::new_spanned(msg_expr, "Failed to intern log string.")
                    .to_compile_error()
                    .into();
            }
        };
        (index, s)
    } else {
        return syn::Error::new_spanned(
            msg_expr,
            "The first parameter of the argument needs to be a string literal.",
        )
        .to_compile_error()
        .into();
    };

    let level_ident = match level {
        CuLogLevel::Debug => quote! { Debug },
        CuLogLevel::Info => quote! { Info },
        CuLogLevel::Warning => quote! { Warning },
        CuLogLevel::Error => quote! { Error },
        CuLogLevel::Critical => quote! { Critical },
    };

    // Partition unnamed vs named args (a = b treated as named)
    let mut unnamed_params = Vec::<&Expr>::new();
    let mut named_params = Vec::<(&Expr, &Expr)>::new();

    for expr in exprs_iter {
        if let Expr::Assign(ExprAssign { left, right, .. }) = expr {
            named_params.push((left, right));
        } else {
            unnamed_params.push(expr);
        }
    }

    // Build the CuLogEntry population tokens
    let unnamed_prints = unnamed_params.iter().map(|value| {
        quote! {
            let param = to_value(#value).expect("Failed to convert a parameter to a Value");
            log_entry.add_param(ANONYMOUS, param);
        }
    });

    let mut named_prints = Vec::with_capacity(named_params.len());
    for (name, value) in &named_params {
        let name_str = quote!(#name).to_string();
        let idx = match intern_string(&name_str) {
            Some(idx) => idx,
            None => {
                return syn::Error::new_spanned(name, "Failed to intern log parameter name.")
                    .to_compile_error()
                    .into();
            }
        };
        named_prints.push(quote! {
            let param = to_value(#value).expect("Failed to convert a parameter to a Value");
            log_entry.add_param(#idx, param);
        });
    }

    // ---------- For baremetal: build a defmt format literal and arg list ----------
    // defmt line: "<msg> | a={:?}, b={:?}, arg0={:?} ..."
    #[cfg(feature = "textlogs")]
    let (defmt_fmt_lit, defmt_args_unnamed_ts, defmt_args_named_ts, defmt_available) = {
        let defmt_fmt_lit = {
            let mut s = msg_str.clone();
            if !named_params.is_empty() {
                s.push_str(" |");
            }
            for (name, _) in named_params.iter() {
                let name_str = quote!(#name).to_string();
                s.push(' ');
                s.push_str(&name_str);
                s.push_str("={:?}");
            }
            syn::LitStr::new(&s, msg_expr.span())
        };

        let defmt_args_unnamed_ts: Vec<TokenStream2> =
            unnamed_params.iter().map(|e| quote! { #e }).collect();
        let defmt_args_named_ts: Vec<TokenStream2> = named_params
            .iter()
            .map(|(_, rhs)| quote! { #rhs })
            .collect();

        let defmt_available = crate_name("defmt").is_ok();

        (
            defmt_fmt_lit,
            defmt_args_unnamed_ts,
            defmt_args_named_ts,
            defmt_available,
        )
    };

    #[cfg(feature = "textlogs")]
    fn defmt_macro_path(level: CuLogLevel) -> TokenStream2 {
        let macro_ident = match level {
            CuLogLevel::Debug => quote! { defmt_debug },
            CuLogLevel::Info => quote! { defmt_info },
            CuLogLevel::Warning => quote! { defmt_warn },
            CuLogLevel::Error => quote! { defmt_error },
            CuLogLevel::Critical => quote! { defmt_error },
        };

        let (base, use_prelude) = match crate_name("cu29-log") {
            Ok(FoundCrate::Name(name)) => {
                let ident = proc_macro2::Ident::new(&name, Span::call_site());
                (quote! { ::#ident }, false)
            }
            Ok(FoundCrate::Itself) => (quote! { crate }, false),
            Err(_) => match crate_name("cu29") {
                Ok(FoundCrate::Name(name)) => {
                    let ident = proc_macro2::Ident::new(&name, Span::call_site());
                    (quote! { ::#ident }, true)
                }
                Ok(FoundCrate::Itself) => (quote! { crate }, true),
                Err(_) => (quote! { ::cu29_log }, false),
            },
        };

        if use_prelude {
            quote! { #base::prelude::#macro_ident }
        } else {
            quote! { #base::#macro_ident }
        }
    }

    // Runtime logging path (unchanged)
    #[cfg(not(debug_assertions))]
    let log_stmt = quote! { let r = log(&mut log_entry); };

    #[cfg(debug_assertions)]
    let log_stmt: TokenStream2 = {
        let keys: Vec<_> = named_params
            .iter()
            .map(|(name, _)| {
                let name_str = quote!(#name).to_string();
                syn::LitStr::new(&name_str, name.span())
            })
            .collect();
        quote! {
            let r = log_debug_mode(&mut log_entry, #msg_str, &[#(#keys),*]);
        }
    };

    let error_handling: Option<TokenStream2> = Some(quote! {
        if let Err(_e) = r {
            let _ = &_e;
        }
    });

    #[cfg(feature = "textlogs")]
    let defmt_macro: TokenStream2 = defmt_macro_path(level);

    #[cfg(feature = "textlogs")]
    let maybe_inject_defmt: Option<TokenStream2> = if STD || !defmt_available {
        None // defmt is only emitted in no-std builds.
    } else {
        Some(quote! {
            #defmt_macro!(#defmt_fmt_lit, #(#defmt_args_unnamed_ts,)* #(#defmt_args_named_ts,)*);
        })
    };

    #[cfg(not(feature = "textlogs"))]
    let maybe_inject_defmt: Option<TokenStream2> = None; // defmt emission disabled

    // Emit both: defmt (conditionally) + Copper structured logging
    quote! {{
        let mut log_entry = CuLogEntry::new(#index, CuLogLevel::#level_ident);
        #(#unnamed_prints)*
        #(#named_prints)*

        #maybe_inject_defmt

        #log_stmt
        #error_handling
    }}
    .into()
}

/// This macro is used to log a debug message with parameters.
/// The first parameter is a string literal that represents the message to be logged.
/// Only `{}` is supported as a placeholder for parameters.
/// The rest of the parameters are the values to be logged.
/// The parameters can be named or unnamed.
/// Named parameters are specified as `name = value`.
/// Unnamed parameters are specified as `value`.
/// # Example
/// ```ignore
/// use cu29_log_derive::debug;
/// let a = 1;
/// let b = 2;
/// debug!("a = {}, b = {}", my_value = a, b); // named and unnamed parameters
/// ```
///
/// You can retrieve this data using the log_reader generated with your project and giving it the
/// unified .copper log file and the string index file generated at compile time.
///
/// Note: In debug mode, the log will also be printed to the console. (ie slooow).
/// In release mode, the log will be only be written to the unified logger.
///
/// This macro will be compiled out if the max log level is set to a level higher than Debug.
#[cfg(any(feature = "log-level-debug", cu29_default_log_level_debug))]
#[proc_macro]
pub fn debug(input: TokenStream) -> TokenStream {
    create_log_entry(input, CuLogLevel::Debug)
}

/// This macro is used to log an info message with parameters.
/// The first parameter is a string literal that represents the message to be logged.
/// Only `{}` is supported as a placeholder for parameters.
/// The rest of the parameters are the values to be logged.
///
/// This macro will be compiled out if the max log level is set to a level higher than Info.
#[cfg(any(feature = "log-level-debug", feature = "log-level-info",))]
#[proc_macro]
pub fn info(input: TokenStream) -> TokenStream {
    create_log_entry(input, CuLogLevel::Info)
}

/// This macro is used to log a warning message with parameters.
/// The first parameter is a string literal that represents the message to be logged.
/// Only `{}` is supported as a placeholder for parameters.
/// The rest of the parameters are the values to be logged.
///
/// This macro will be compiled out if the max log level is set to a level higher than Warning.
#[cfg(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
))]
#[proc_macro]
pub fn warning(input: TokenStream) -> TokenStream {
    create_log_entry(input, CuLogLevel::Warning)
}

/// This macro is used to log an error message with parameters.
/// The first parameter is a string literal that represents the message to be logged.
/// Only `{}` is supported as a placeholder for parameters.
/// The rest of the parameters are the values to be logged.
///
/// This macro will be compiled out if the max log level is set to a level higher than Error.
#[cfg(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
    feature = "log-level-error",
))]
#[proc_macro]
pub fn error(input: TokenStream) -> TokenStream {
    create_log_entry(input, CuLogLevel::Error)
}

/// This macro is used to log a critical message with parameters.
/// The first parameter is a string literal that represents the message to be logged.
/// Only `{}` is supported as a placeholder for parameters.
/// The rest of the parameters are the values to be logged.
///
/// This macro is always compiled in, regardless of the max log level setting.
#[cfg(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
    feature = "log-level-error",
    feature = "log-level-critical",
))]
#[proc_macro]
pub fn critical(input: TokenStream) -> TokenStream {
    create_log_entry(input, CuLogLevel::Critical)
}

// Provide empty implementations for macros that are compiled out
#[cfg(not(any(feature = "log-level-debug", cu29_default_log_level_debug)))]
#[proc_macro]
pub fn debug(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    reference_unused_variables(input)
}

#[cfg(not(any(feature = "log-level-debug", feature = "log-level-info",)))]
#[proc_macro]
pub fn info(input: TokenStream) -> TokenStream {
    reference_unused_variables(input)
}

#[cfg(not(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
)))]
#[proc_macro]
pub fn warning(input: TokenStream) -> TokenStream {
    reference_unused_variables(input)
}

#[cfg(not(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
    feature = "log-level-error",
)))]
#[proc_macro]
pub fn error(input: TokenStream) -> TokenStream {
    reference_unused_variables(input)
}

#[cfg(not(any(
    feature = "log-level-debug",
    feature = "log-level-info",
    feature = "log-level-warning",
    feature = "log-level-error",
    feature = "log-level-critical",
)))]
#[proc_macro]
pub fn critical(input: TokenStream) -> TokenStream {
    reference_unused_variables(input)
}

/// Interns a string
/// For example:
///
/// let string_number: u32 = intern!("my string");
///
/// will store "my string" in the interned string db at compile time and return the index of the string.
#[proc_macro]
pub fn intern(input: TokenStream) -> TokenStream {
    let expr = match syn::parse::<Expr>(input) {
        Ok(expr) => expr,
        Err(err) => return err.to_compile_error().into(),
    };
    let index = if let Expr::Lit(ExprLit {
        lit: Lit::Str(msg), ..
    }) = &expr
    {
        let msg = msg.value();
        match intern_string(&msg) {
            Some(index) => index,
            None => {
                return syn::Error::new_spanned(&expr, "Failed to intern log string.")
                    .to_compile_error()
                    .into();
            }
        }
    } else {
        return syn::Error::new_spanned(
            &expr,
            "The first parameter of the argument needs to be a string literal.",
        )
        .to_compile_error()
        .into();
    };
    quote! { #index }.into()
}