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
//! Macros part of the stlog logging framework

#![deny(warnings)]

extern crate proc_macro;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;

use proc_macro::TokenStream;

use syn::ItemStatic;

/// An attribute to declare a global logger
///
/// This attribute can only be applied to `static` variables that implement the
/// [`GlobalLog`](../stlog/trait.GlobalLog.html) trait.
#[proc_macro_attribute]
pub fn global_logger(args: TokenStream, input: TokenStream) -> TokenStream {
    let var = parse_macro_input!(input as ItemStatic);

    assert_eq!(
        args.to_string(),
        "",
        "`global_logger` attribute takes no arguments"
    );

    assert!(
        var.mutability.is_none(),
        "`#[global_logger]` can't be used on `static mut` variables"
    );

    let attrs = var.attrs;
    let vis = var.vis;
    let ident = var.ident;
    let ty = var.ty;
    let expr = var.expr;

    // TODO use this when rust-lang/rust#54451 lands
    // quote!(
    //     #(#attrs)*
    //     #vis static #ident: #ty = {
    //         #[export_name = "stlog::GLOBAL_LOGGER"]
    //         static __STLOGGER__: &stlog::GlobalLog = &#ident;

    //         #expr
    //     };
    // ).into()

    quote!(
        #(#attrs)*
        #vis static #ident: #ty = #expr;

        #[export_name = "stlog::GLOBAL_LOGGER"]
        pub static __STLOG_GLOBAL_LOGGER__: &(stlog::GlobalLog) = {
            &#ident
        };
    ).into()
}