| 1 |
use proc_macro::TokenStream; |
| 2 |
use proc_macro2::Span; |
| 3 |
use quote::quote; |
| 4 |
use syn::{parse_macro_input, Fields, ItemStruct}; |
| 5 |
|
| 6 |
pub(crate) fn expand(args: TokenStream, item: TokenStream) -> TokenStream { |
| 7 |
let strukt = parse_macro_input!(item as ItemStruct); |
| 8 |
|
| 9 |
if !args.is_empty() { |
| 10 |
return syn::Error::new( |
| 11 |
Span::call_site(), |
| 12 |
"`#[global_logger]` attribute takes no arguments", |
| 13 |
) |
| 14 |
.into_compile_error() |
| 15 |
.into(); |
| 16 |
} |
| 17 |
|
| 18 |
if let Err(err) = validate(&strukt) { |
| 19 |
return err.into_compile_error().into(); |
| 20 |
} |
| 21 |
|
| 22 |
codegen(&strukt) |
| 23 |
} |
| 24 |
|
| 25 |
fn validate(strukt: &ItemStruct) -> syn::Result<()> { |
| 26 |
let is_unit_struct = matches!(strukt.fields, Fields::Unit); |
| 27 |
|
| 28 |
if !strukt.generics.params.is_empty() |
| 29 |
|| strukt.generics.where_clause.is_some() |
| 30 |
|| !is_unit_struct |
| 31 |
{ |
| 32 |
Err(syn::Error::new( |
| 33 |
strukt.ident.span(), |
| 34 |
"struct must be a non-generic unit struct (e.g. `struct S;`)", |
| 35 |
)) |
| 36 |
} else { |
| 37 |
Ok(()) |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
fn codegen(strukt: &ItemStruct) -> TokenStream { |
| 42 |
let attrs = &strukt.attrs; |
| 43 |
let ident = &strukt.ident; |
| 44 |
let vis = &strukt.vis; |
| 45 |
|
| 46 |
quote!( |
| 47 |
#(#attrs)* |
| 48 |
#vis struct #ident; |
| 49 |
|
| 50 |
#[inline(never)] |
| 51 |
#[no_mangle] |
| 52 |
unsafe fn _defmt_acquire() { |
| 53 |
<#ident as defmt::Logger>::acquire() |
| 54 |
} |
| 55 |
|
| 56 |
#[inline(never)] |
| 57 |
#[no_mangle] |
| 58 |
unsafe fn _defmt_flush() { |
| 59 |
<#ident as defmt::Logger>::flush() |
| 60 |
} |
| 61 |
|
| 62 |
#[inline(never)] |
| 63 |
#[no_mangle] |
| 64 |
unsafe fn _defmt_release() { |
| 65 |
<#ident as defmt::Logger>::release() |
| 66 |
} |
| 67 |
|
| 68 |
#[inline(never)] |
| 69 |
#[no_mangle] |
| 70 |
unsafe fn _defmt_write(bytes: &[u8]) { |
| 71 |
<#ident as defmt::Logger>::write(bytes) |
| 72 |
} |
| 73 |
) |
| 74 |
.into() |
| 75 |
} |