Skip to main content

bitflags2_derive/
lib.rs

1use proc_macro::TokenStream;
2use syn::{ItemEnum, parse_macro_input};
3
4mod codegen;
5mod model;
6mod parse;
7
8/// Expands an enum into a compact bitflag type.
9///
10/// The `#[flag]` attributes on variants are helper markers consumed by this
11/// attribute macro. They are intentionally not exported as standalone macros,
12/// so using `#[flag]` without `#[flags]` fails at compile time.
13///
14/// `#[flags]` optionally accepts an explicit backing integer type, e.g.
15/// `#[flags(u32)]`. Without an argument the smallest type that fits every
16/// flag value is chosen automatically, matching prior behavior.
17#[proc_macro_attribute]
18pub fn flags(attr: TokenStream, item: TokenStream) -> TokenStream {
19    let input = parse_macro_input!(item as ItemEnum);
20
21    let backing = if attr.is_empty() {
22        None
23    } else {
24        Some(parse_macro_input!(attr as parse::BackingType))
25    };
26
27    match parse::parse_flags(input, backing) {
28        Ok(flags) => codegen::generate(flags).into(),
29        Err(error) => error.to_compile_error().into(),
30    }
31}