#macro-derive #attributes #derivation #enums #macro-attr #struct #traits

no-std macro-attr-2018

This crate provides the macro_attr! macro that enables the use of custom, macro-based attributes and derivations

15 releases (stable)

3.0.0 Jul 24, 2023
2.1.2 May 26, 2022
1.1.2 May 6, 2022
1.1.1 Jul 15, 2021
0.3.3 Sep 6, 2020

#232 in Rust patterns

Download history 755/week @ 2023-11-21 802/week @ 2023-11-28 646/week @ 2023-12-05 653/week @ 2023-12-12 614/week @ 2023-12-19 488/week @ 2023-12-26 645/week @ 2024-01-02 615/week @ 2024-01-09 376/week @ 2024-01-16 295/week @ 2024-01-23 169/week @ 2024-01-30 627/week @ 2024-02-06 951/week @ 2024-02-13 914/week @ 2024-02-20 941/week @ 2024-02-27 793/week @ 2024-03-05

3,849 downloads per month
Used in 16 crates (10 directly)

MIT/Apache

13KB
197 lines

maintenance: passively maintained

macro-attr-2018

The macro-attr modern fork.

This crate provides the macro_attr! macro that enables the use of custom, macro-based derivations.

The macro_attr! macro should be used to wrap an entire single item (enum, struct, etc.) declaration, including its attributes (both derive and others). All derivations which whose names end with ! will be assumed to be implemented by macros, and treated accordingly.

use macro_attr_2018::macro_attr;

// Define some traits to be derived.

trait TypeName {
    fn type_name() -> &'static str;
}

trait ReprType {
    type Repr;
}

// Define macros which derive implementations of these macros.

macro_rules! TypeName {
    // We can support any kind of item we want.
    (() $vis:vis enum $name:ident $($tail:tt)+) => { TypeName! { @impl $name } };
    (() $vis:vis struct $name:ident $($tail:tt)+) => { TypeName! { @impl $name } };

    // Inner rule to cut down on repetition.
    (@impl $name:ident) => {
        impl TypeName for $name {
            fn type_name() -> &'static str { stringify!($name) }
        }
    };
}

macro_rules! ReprType {
    // Note that we use a "derivation argument" here for the `$repr` type.
    (($repr:ty) $vis:vis enum $name:ident $($tail:tt)+) => {
        impl ReprType for $name {
            type Repr = $repr;
        }
    };
}

// Derive.

macro_attr! {
    #[derive(TypeName!, ReprType!(u16))]
    #[repr(u16)]
    enum SomeEnum { A, B, C, D }
}

No runtime deps