1个不稳定版本

0.0.1 2022年8月15日

#24 in #attr


2 个库中使用

GPL-3.0-or-later

43KB
1K SLoC

Kefta

使用proc-macros简化属性解析

crates.io badge docs.rs badge Downloads badge

主要功能

  • 为轻松解析结构提供derive宏
  • 内置的“合理”错误消息
  • 内置属性解析
  • 可选的syn支持

功能开关

  • literal - 文本解析
  • util - 预制类型和实用特性
  • syn - 通过Syn<impl syn::Parse>支持syn

示例

use kefta::{Attr, parse_attr};

// derive `Attr` onto your struct
#[derive(Attr)]
struct MyAttrs {
    // a marker field,
    alive: bool,

    // an optional field
    #[attr(optional)]
    name: Option<String>,

    // a required field
    #[attr(required)]
    value: i32,

    // a default field (defaults to 0)
    count: u32,

    // a renamed field
    #[attr(optional, name="desc")]
    description: Option<String>,

    // a field with an alias
    #[attr(alias="color")]
    colour: Option<String>,

    // a field with multiple values
    #[attr(multiple)]
    jobs: Vec<String>,

    // an optional, aliased field, with multiple values
    #[attr(multiple, optional, alias="chores")]
    tasks: Option<Vec<String>>,
    /* you get the point */
}

// parse in your derive-macro
// * this uses the syn crate and `syn` feature
#[proc_macro_derive(Human, attributes(human))]
pub fn test_macro(item: TokenStream) -> TokenStream {
    // parse with `syn`
    let input = syn::parse_macro_input!(item as DeriveInput);

    // parse the attributes with the `parse_attr!` macro
    // it contains a `return TokenStream`, so you don't have to handle errors.
    let attrs = parse_attr!(input.attrs => MyAttrs);

    // print out one of our fields
    println!("Name:  {:?}", attrs.name);

    TokenStream::new()
}

您可以使用属性如下

#[derive(Human)]
#[human(name="Jimmy", value=10, alive)]
#[human(jobs="foo", jobs="bar", jobs="baz")]
pub struct Jimmy;

依赖项

~14–440KB
~10K SLoC