Skip to main content

chapa_macros/
lib.rs

1//! Procedural macro implementation for the `chapa` bitfield crate.
2//!
3//! This crate is not meant to be used directly. Use the `chapa` crate instead,
4//! which re-exports the [`bitfield`] attribute macro and [`BitEnum`] derive
5//! macro from here.
6
7mod bit_enum;
8mod codegen;
9mod model;
10mod ordering;
11mod parse;
12mod validate;
13
14use proc_macro::TokenStream;
15
16use model::BitfieldArgs;
17
18/// The `#[bitfield]` attribute macro.
19///
20/// Transforms an annotated struct into a zero-overhead bitfield backed by a
21/// single primitive integer. See the `chapa` crate documentation for full
22/// usage examples and available options.
23#[proc_macro_attribute]
24pub fn bitfield(attr: TokenStream, item: TokenStream) -> TokenStream {
25    match bitfield_impl(attr, item) {
26        Ok(ts) => ts,
27        Err(e) => e.to_compile_error().into(),
28    }
29}
30
31/// Parses the attribute + struct, validates semantics, and drives code generation.
32fn bitfield_impl(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {
33    let args = syn::parse::<BitfieldArgs>(attr)?;
34    let item_struct = syn::parse::<syn::ItemStruct>(item)?;
35
36    let def = parse::parse_struct(&args, &item_struct)?;
37    validate::validate(&def)?;
38    let output = codegen::generate(&def);
39
40    Ok(output.into())
41}
42
43/// Derive macro that implements `chapa::BitField` for C-like enums.
44///
45/// Also auto-derives `Copy` and `Clone` (zero-cost for unit-variant enums).
46#[proc_macro_derive(BitEnum)]
47pub fn bit_enum(input: TokenStream) -> TokenStream {
48    match bit_enum_impl(input) {
49        Ok(ts) => ts,
50        Err(e) => e.to_compile_error().into(),
51    }
52}
53
54fn bit_enum_impl(input: TokenStream) -> syn::Result<TokenStream> {
55    let input = syn::parse::<syn::DeriveInput>(input)?;
56    bit_enum::generate(input).map(Into::into)
57}