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
use proc_macro::TokenStream;
use proc_macro_error::{abort, abort_call_site};
use quote::quote;
use syn::{parse_macro_input, Fields, ItemStruct};

pub(crate) fn expand(args: TokenStream, item: TokenStream) -> TokenStream {
    if !args.is_empty() {
        abort_call_site!("`#[global_logger]` attribute takes no arguments")
    }

    let strukt = parse_macro_input!(item as ItemStruct);

    validate(&strukt);

    codegen(&strukt)
}

fn validate(strukt: &ItemStruct) {
    let is_unit_struct = matches!(strukt.fields, Fields::Unit);

    if !strukt.generics.params.is_empty()
        || strukt.generics.where_clause.is_some()
        || !is_unit_struct
    {
        abort!(
            strukt,
            "struct must be a non-generic unit struct (e.g. `struct S;`)"
        );
    }
}

fn codegen(strukt: &ItemStruct) -> TokenStream {
    let attrs = &strukt.attrs;
    let ident = &strukt.ident;
    let vis = &strukt.vis;

    quote!(
        #(#attrs)*
        #vis struct #ident;

        #[inline(never)]
        #[no_mangle]
        unsafe fn _defmt_acquire()  {
            <#ident as defmt::Logger>::acquire()
        }

        #[inline(never)]
        #[no_mangle]
        unsafe fn _defmt_flush()  {
            <#ident as defmt::Logger>::flush()
        }

        #[inline(never)]
        #[no_mangle]
        unsafe fn _defmt_release()  {
            <#ident as defmt::Logger>::release()
        }

        #[inline(never)]
        #[no_mangle]
        unsafe fn _defmt_write(bytes: &[u8])  {
            <#ident as defmt::Logger>::write(bytes)
        }
    )
    .into()
}