How do I create a proc_macro_attribute?

前端 未结 2 1454
庸人自扰
庸人自扰 2021-01-14 03:13

Now that proc_macros have been stabilized, how does one create such a thing?

From what I\'ve seen, there\'s the option of putting a #[proc_macro_a

2条回答
  •  情话喂你
    2021-01-14 03:20

    If I understand RFC 1566 correctly, you:

    • Create a crate of type proc_macro, i.e. its Cargo.toml should contain

      [lib]
      proc-macro = true
      
    • In that crate, create the implementation, annotated with #[proc_macro_attribute]. The #[proc_macro] for function-like macros and #[proc_macro_derive] for custom derives work the same, except they only have one TokenStream argument. These are defined in the proc_macro crate.

      The first token stream is the arguments in the attribute, the second is the body of the annotated item.

    • Then in the crate that wants to use the macro, simply depend on the proc_macro crate and import it with #[macro_use] attribute (#[macro_use] extern crate…).

    That should be enough.

    The appendix in Book should be extended to mention the other proc macro types beyond #[proc_macro_derive]. That it does not is probably a bug.

提交回复
热议问题