| 1 |
use defmt_parser::ParserMode; |
| 2 |
use proc_macro::TokenStream; |
| 3 |
use quote::quote; |
| 4 |
use syn::{parse_macro_input, parse_quote}; |
| 5 |
|
| 6 |
use crate::{construct, function_like::log}; |
| 7 |
|
| 8 |
use self::args::Args; |
| 9 |
|
| 10 |
mod args; |
| 11 |
|
| 12 |
pub(crate) fn expand(args: TokenStream) -> TokenStream { |
| 13 |
let Args { |
| 14 |
formatter, |
| 15 |
log_args, |
| 16 |
.. |
| 17 |
} = parse_macro_input!(args as Args); |
| 18 |
|
| 19 |
let format_string = log_args.format_string.value(); |
| 20 |
let fragments = match defmt_parser::parse(&format_string, ParserMode::Strict) { |
| 21 |
Ok(args) => args, |
| 22 |
Err(e) => { |
| 23 |
return syn::Error::new(log_args.format_string.span(), format!("{}", e)) |
| 24 |
.into_compile_error() |
| 25 |
.into() |
| 26 |
} |
| 27 |
}; |
| 28 |
|
| 29 |
let formatting_exprs: Vec<_> = log_args |
| 30 |
.formatting_args |
| 31 |
.map(|punctuated| punctuated.into_iter().collect()) |
| 32 |
.unwrap_or_default(); |
| 33 |
|
| 34 |
let log::Codegen { patterns, exprs } = match log::Codegen::new( |
| 35 |
&fragments, |
| 36 |
formatting_exprs.len(), |
| 37 |
log_args.format_string.span(), |
| 38 |
) { |
| 39 |
Ok(val) => val, |
| 40 |
Err(err) => return err.into_compile_error().into(), |
| 41 |
}; |
| 42 |
|
| 43 |
let format_tag = |
| 44 |
construct::interned_string(&format_string, "write", false, None, &parse_quote!(defmt)); |
| 45 |
quote!({ |
| 46 |
let _typecheck_formatter: defmt::Formatter<'_> = #formatter; |
| 47 |
match (#(&(#formatting_exprs)),*) { |
| 48 |
(#(#patterns),*) => { |
| 49 |
defmt::export::istr(&#format_tag); |
| 50 |
#(#exprs;)* |
| 51 |
} |
| 52 |
} |
| 53 |
}) |
| 54 |
.into() |
| 55 |
} |