| 1 |
use defmt_parser::ParserMode; |
| 2 |
use proc_macro::TokenStream; |
| 3 |
use proc_macro2::TokenStream as TokenStream2; |
| 4 |
use quote::quote; |
| 5 |
use syn::{parse_macro_input, parse_quote}; |
| 6 |
|
| 7 |
use crate::construct; |
| 8 |
use crate::function_like::log::{Args, Codegen}; |
| 9 |
|
| 10 |
pub(crate) fn expand(args: TokenStream) -> TokenStream { |
| 11 |
let parsed = parse_macro_input!(args as Args); |
| 12 |
expand_parsed(parsed) |
| 13 |
.unwrap_or_else(syn::Error::into_compile_error) |
| 14 |
.into() |
| 15 |
} |
| 16 |
|
| 17 |
pub(crate) fn expand_parsed(args: Args) -> syn::Result<TokenStream2> { |
| 18 |
let format_string = args.format_string.value(); |
| 19 |
let fragments = match defmt_parser::parse(&format_string, ParserMode::Strict) { |
| 20 |
Ok(args) => args, |
| 21 |
Err(e @ defmt_parser::Error::UnknownDisplayHint(_)) => return Err(syn::Error::new( |
| 22 |
args.format_string.span(), |
| 23 |
format!( |
| 24 |
"{e}\n = help: {help}", |
| 25 |
help = "`defmt` uses a slightly different syntax than regular formatting in Rust. See https://defmt.ferrous-systems.com/macros.html for more details." |
| 26 |
) |
| 27 |
)), |
| 28 |
Err(e) => return Err(syn::Error::new(args.format_string.span(), format!("{}", e))), // No extra help |
| 29 |
}; |
| 30 |
|
| 31 |
let formatting_exprs = args |
| 32 |
.formatting_args |
| 33 |
.map(|punctuated| punctuated.into_iter().collect::<Vec<_>>()) |
| 34 |
.unwrap_or_default(); |
| 35 |
|
| 36 |
let Codegen { patterns, exprs } = Codegen::new( |
| 37 |
&fragments, |
| 38 |
formatting_exprs.len(), |
| 39 |
args.format_string.span(), |
| 40 |
)?; |
| 41 |
|
| 42 |
let header = |
| 43 |
construct::interned_string(&format_string, "println", true, None, &parse_quote!(defmt)); |
| 44 |
let content = if exprs.is_empty() { |
| 45 |
quote!( |
| 46 |
defmt::export::acquire_header_and_release(&#header); |
| 47 |
) |
| 48 |
} else { |
| 49 |
quote!( |
| 50 |
// safety: will be released a few lines further down |
| 51 |
unsafe { defmt::export::acquire_and_header(&#header); }; |
| 52 |
#(#exprs;)* |
| 53 |
// safety: acquire() was called a few lines above |
| 54 |
unsafe { defmt::export::release() } |
| 55 |
) |
| 56 |
}; |
| 57 |
Ok(quote!({ |
| 58 |
match (#(&(#formatting_exprs)),*) { |
| 59 |
(#(#patterns),*) => { |
| 60 |
#content |
| 61 |
} |
| 62 |
} |
| 63 |
})) |
| 64 |
} |