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

no-std macro-attr

本软件包提供了 macro_attr! 宏,该宏允许使用基于宏的自定义属性和派生。取代了 custom_derive 软件包。

1 个不稳定版本

使用旧的 Rust 2015

0.2.0 2016 年 11 月 21 日

#2057Rust 模式

Download history 209/week @ 2024-03-24 259/week @ 2024-03-31 153/week @ 2024-04-07 198/week @ 2024-04-14 165/week @ 2024-04-21 148/week @ 2024-04-28 174/week @ 2024-05-05 185/week @ 2024-05-12 162/week @ 2024-05-19 170/week @ 2024-05-26 162/week @ 2024-06-02 162/week @ 2024-06-09 178/week @ 2024-06-16 174/week @ 2024-06-23 145/week @ 2024-06-30 91/week @ 2024-07-07

611 次每月下载
11 个软件包中使用了 (10 直接)

MIT/Apache

54KB
1K SLoC

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

macro-attr

本软件包提供了 macro_attr! 宏,该宏允许使用基于宏的自定义属性和派生。取代了 custom_derive 软件包。

链接

兼容性

macro-attr 与 Rust 1.2 及更高版本兼容。

示例

#[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)");
}

许可证

根据您的要求,许可协议可以是

任选其一。

贡献

除非您明确声明,否则您有意提交的任何贡献,包括在您的工作中包含的内容,都应按上述方式双许可,而不附加任何额外条款或条件。

无运行时依赖