procmeta

Crates.ioprocmeta
lib.rsprocmeta
version0.3.5
sourcesrc
created_at2024-02-15 01:15:33.737671
updated_at2024-05-03 02:46:47.036499
descriptionintegration procmeta-core and procmeta-proc
homepage
repository
max_upload_size
id1140483
size12,353
(git-lloyd)

documentation

README

描述

用于rust过程宏开发辅助工具包

使用

派生宏 GetTokenStream

用于生成获取改类型值的token stream,如:

    #[test]
    fn test_token_stream() {
        #[derive(GetTokenStream)]
        pub enum Ass {
            S(Student),
        }

        #[derive(GetTokenStream)]
        pub struct Student {
            pub name: String,
            pub age: i32,
        }
        let student = Student {
            name: "lloyd".to_string(),
            age: 18,
        };

        let a = Ass::S(student);
        println!("{}", a.get_token_stream());
    }

输出结果为: Ass :: S (Student { name : "lloyd" . into () , age : 18i32 , } ,)

派生宏 MetaParser

用于解析宏辅助参数,将参数元数据解析为特定的枚举

  • 指定解析的参数名称使用[name]进行标注
  • 元组项的类型没有实现parse stream时,可使用[converter]进行转换
  • 带名的结构体使用类型的FromMetaExpr实现,调用try_from_expr方法进行获取 如:
    #[test]
    fn test_meta_parser() {
        #[derive(MetaParser)]
        enum Context {
            #[name("note")]
            Note(#[converter(LitStr)] String),

            #[name("note")]
            NoteNameSize { name: LitStr, size: LitInt },

            #[name("note")]
            NoteName { name: LitStr },
        }

        let input: ItemStruct = parse_quote! {
            #[note("111")]
            #[note(name = "222", size = 18)]
            #[note(name = "333")]
            pub struct MyStruct {
                pub name: String,
            }
        };
        let attrs = input.attrs;
        for attr in attrs {
            let context = Context::parse(&attr.meta);
            if let Ok(context) = context {
                match context {
                    Context::Note(name) => {
                        println!("{}", name);
                    }
                    Context::NoteNameSize { name, size } => {
                        println!(
                            "name = {}, size = {}",
                            name.value(),
                            size.base10_parse::<i64>().unwrap()
                        );
                    }
                    Context::NoteName { name } => {
                        println!("name = {}", name.value());
                    }
                }
            }
        }
    }
Commit count: 0

cargo fmt