#macro-derive #attributes #macro #derive #custom-derive #custom

no-std macro-attr

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

1 unstable release

Uses old Rust 2015

0.2.0 Nov 21, 2016

#2011 in Rust patterns

Download history 182/week @ 2024-07-19 131/week @ 2024-07-26 146/week @ 2024-08-02 162/week @ 2024-08-09 132/week @ 2024-08-16 112/week @ 2024-08-23 238/week @ 2024-08-30 150/week @ 2024-09-06 126/week @ 2024-09-13 166/week @ 2024-09-20 190/week @ 2024-09-27 105/week @ 2024-10-04 131/week @ 2024-10-11 214/week @ 2024-10-18 179/week @ 2024-10-25 135/week @ 2024-11-01

669 downloads per month
Used in 11 crates (10 directly)

MIT/Apache

54KB
1K SLoC

Rust 841 SLoC // 0.3% comments Python 353 SLoC // 0.1% comments

macro-attr

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

Links

Compatibility

macro-attr is compatible with Rust 1.2 and higher.

Example

#[macro_use] extern crate 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.
    (() $(pub)* enum $name:ident $($tail:tt)*) => { TypeName! { @impl $name } };
    (() $(pub)* 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) $(pub)* enum $name:ident $($tail:tt)*) => {
        impl ReprType for $name {
            type Repr = $repr;
        }
    };
}

// Here is a macro that *modifies* the item.

macro_rules! rename_to {
    (
        ($new_name:ident),
        then $cb:tt,
        $(#[$($attrs:tt)*])*
        enum $_old_name:ident $($tail:tt)*
    ) => {
        macro_attr_callback! {
            $cb,
            $(#[$($attrs)*])*
            enum $new_name $($tail)*
        }
    };
}

macro_attr! {
    #[allow(dead_code)]
    #[derive(Clone, Copy, Debug, ReprType!(u8), TypeName!)]
    #[rename_to!(Bar)]
    #[repr(u8)]
    enum Foo { A, B }
}

fn main() {
    let bar = Bar::B;
    let v = bar as <Bar as ReprType>::Repr;
    let msg = format!("{}: {:?} ({:?})", Bar::type_name(), bar, v);
    assert_eq!(msg, "Bar: B (1)");
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.

No runtime deps