| 1 |
use defmt_parser::ParserMode; |
| 2 |
use proc_macro::TokenStream; |
| 3 |
use quote::format_ident; |
| 4 |
use quote::quote; |
| 5 |
use syn::parse_macro_input; |
| 6 |
|
| 7 |
use crate::{construct, function_like::log}; |
| 8 |
|
| 9 |
pub(crate) fn expand(args: TokenStream) -> TokenStream { |
| 10 |
let args = parse_macro_input!(args as log::Args); |
| 11 |
|
| 12 |
let format_string = args.format_string.value(); |
| 13 |
|
| 14 |
let fragments = match defmt_parser::parse(&format_string, ParserMode::Strict) { |
| 15 |
Ok(args) => args, |
| 16 |
Err(e) => { |
| 17 |
return syn::Error::new(args.format_string.span(), format!("{}", e)) |
| 18 |
.into_compile_error() |
| 19 |
.into() |
| 20 |
} |
| 21 |
}; |
| 22 |
|
| 23 |
let formatting_exprs: Vec<_> = args |
| 24 |
.formatting_args |
| 25 |
.map(|punctuated| punctuated.into_iter().collect()) |
| 26 |
.unwrap_or_default(); |
| 27 |
|
| 28 |
let log::Codegen { patterns, exprs } = match log::Codegen::new( |
| 29 |
&fragments, |
| 30 |
formatting_exprs.len(), |
| 31 |
args.format_string.span(), |
| 32 |
) { |
| 33 |
Ok(val) => val, |
| 34 |
Err(err) => return err.into_compile_error().into(), |
| 35 |
}; |
| 36 |
|
| 37 |
let var_name = format_ident!("S"); |
| 38 |
let var_item = construct::static_variable(&var_name, &format_string, "timestamp", None); |
| 39 |
|
| 40 |
quote!( |
| 41 |
const _: () = { |
| 42 |
#[export_name = "_defmt_timestamp"] |
| 43 |
#[inline(never)] |
| 44 |
fn defmt_timestamp(fmt: defmt::Formatter<'_>) { |
| 45 |
match (#(&(#formatting_exprs)),*) { |
| 46 |
(#(#patterns),*) => { |
| 47 |
// NOTE: No format string index, and no finalize call. |
| 48 |
#(#exprs;)* |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
#var_item; |
| 54 |
|
| 55 |
// Unique symbol name to prevent multiple `timestamp!` invocations in the crate graph. |
| 56 |
// Uses `#var_name` to ensure it is not discarded by the linker. |
| 57 |
// This symbol itself is retained via a `EXTERN` directive in the linker script. |
| 58 |
#[no_mangle] |
| 59 |
#[cfg_attr(target_os = "macos", link_section = ".defmt,end.timestamp")] |
| 60 |
#[cfg_attr(not(target_os = "macos"), link_section = ".defmt.end.timestamp")] |
| 61 |
static __DEFMT_MARKER_TIMESTAMP_WAS_DEFINED: &u8 = &#var_name; |
| 62 |
}; |
| 63 |
) |
| 64 |
.into() |
| 65 |
} |