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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! Macros part of the stlog logging framework

#![cfg_attr(feature = "spanned", feature(proc_macro_span))]
#![deny(warnings)]

extern crate proc_macro;

use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::{parse_macro_input, spanned::Spanned, Error, ItemStatic};

#[cfg(feature = "spanned")]
mod spanned;

/// 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);

    if !args.is_empty() {
        return Error::new(
            Span::call_site().into(),
            "`global_logger` attribute takes no arguments",
        )
        .to_compile_error()
        .into();
    }

    if var.mutability.is_some() {
        return Error::new(
            var.span(),
            "`#[global_logger]` can't be used on `static mut` variables",
        )
        .to_compile_error()
        .into();
    }

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

    quote!(
        #(#attrs)*
        #vis static #ident: #ty = {
            #[export_name = "stlog::GLOBAL_LOGGER"]
            static GLOBAL_LOGGER: &stlog::GlobalLog = &#ident;

            #expr
        };
    )
    .into()
}

#[cfg(feature = "spanned")]
#[proc_macro]
pub fn error(input: TokenStream) -> TokenStream {
    spanned::common(input, "error")
}

#[cfg(feature = "spanned")]
#[proc_macro]
pub fn warning(input: TokenStream) -> TokenStream {
    spanned::common(input, "warn")
}

#[cfg(feature = "spanned")]
#[proc_macro]
pub fn info(input: TokenStream) -> TokenStream {
    spanned::common(input, "info")
}

#[cfg(feature = "spanned")]
#[proc_macro]
pub fn debug(input: TokenStream) -> TokenStream {
    spanned::common(input, "debug")
}

#[cfg(feature = "spanned")]
#[proc_macro]
pub fn trace(input: TokenStream) -> TokenStream {
    spanned::common(input, "trace")
}