bitflags_derive_macros/
lib.rs

1/*!
2Implementation details for `bitflags-derive`.
3
4This library isn't intended to be used directly.
5*/
6
7#![deny(missing_docs)]
8
9extern crate proc_macro;
10
11#[macro_use]
12extern crate quote;
13
14mod debug;
15mod display;
16mod from_str;
17
18#[cfg(feature = "serde")]
19mod serde;
20
21/**
22Derive [`Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html).
23
24This macro will use [`to_writer`](https://docs.rs/bitflags/latest/bitflags/parser/fn.to_writer.html) to
25format flags values.
26*/
27#[proc_macro_derive(FlagsDebug)]
28pub fn derive_bitflags_debug(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
29    debug::expand(syn::parse_macro_input!(item as syn::DeriveInput)).unwrap_or_compile_error()
30}
31
32/**
33Derive [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html).
34
35This macro will use [`to_writer`](https://docs.rs/bitflags/latest/bitflags/parser/fn.to_writer.html) to
36format flags values.
37*/
38#[proc_macro_derive(FlagsDisplay)]
39pub fn derive_bitflags_display(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
40    display::expand(syn::parse_macro_input!(item as syn::DeriveInput)).unwrap_or_compile_error()
41}
42
43/**
44Derive [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html).
45
46This macro will use [`from_str`](https://docs.rs/bitflags/latest/bitflags/parser/fn.from_str.html) to
47parse flags values.
48*/
49#[proc_macro_derive(FlagsFromStr)]
50pub fn derive_bitflags_from_str(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
51    from_str::expand(syn::parse_macro_input!(item as syn::DeriveInput)).unwrap_or_compile_error()
52}
53
54/**
55Derive [`Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html).
56*/
57#[cfg(feature = "serde")]
58#[proc_macro_derive(FlagsSerialize)]
59pub fn derive_bitflags_serialize(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
60    serde::serialize::expand(syn::parse_macro_input!(item as syn::DeriveInput))
61        .unwrap_or_compile_error()
62}
63
64/**
65Derive [`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html).
66*/
67#[cfg(feature = "serde")]
68#[proc_macro_derive(FlagsDeserialize)]
69pub fn derive_bitflags_deserialize(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
70    serde::deserialize::expand(syn::parse_macro_input!(item as syn::DeriveInput))
71        .unwrap_or_compile_error()
72}
73
74trait ResultExt {
75    fn unwrap_or_compile_error(self) -> proc_macro::TokenStream;
76}
77
78impl ResultExt for Result<proc_macro2::TokenStream, syn::Error> {
79    fn unwrap_or_compile_error(self) -> proc_macro::TokenStream {
80        proc_macro::TokenStream::from(match self {
81            Ok(item) => item,
82            Err(err) => err.into_compile_error(),
83        })
84    }
85}