procedure
Attribute macros
itemsへouter attributes を定義するマクロ。つまりTrait実装などを継承させるマクロ。
proc_macro_attributeAttributeを使ってpublicなfunctionへ定義する。
example
sqlxより、
#![allow(unused)] fn main() { #[cfg(feature = "macros")] #[proc_macro_attribute] pub fn test(args: TokenStream, input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as syn::ItemFn); match test_attr::expand(args.into(), input) { Ok(ts) => ts.into(), Err(e) => { if let Some(parse_err) = e.downcast_ref::<syn::Error>() { parse_err.to_compile_error().into() } else { let msg = e.to_string(); quote!(::std::compile_error!(#msg)).into() } } } } }
inputはsyn::parseでパースする。syn::parse::Parsetraitを実装済みであれば上記のようにasでパース先を指定できる。(asはキャストなどではなくマクロ定義の一部であることに注意)