use proc_macro_error::*;use proc_macro::TokenStream;use syn::{spanned::Spanned, DeriveInput, ItemStruct, Fields, Attribute , parse_macro_input};use quote::quote;fn process_attrs(attrs: &[Attribute]) -> Vec<Attribute> {attrs.iter().filter_map(|attr| match process_attr(attr) {Ok(res) => Some(res),Err(msg) => {emit_error!(attr, "Invalid attribute: {}", msg);None}}).collect()}fn process_fields(_attrs: &Fields) -> Vec<TokenStream> {// processing fields in pretty much the same way as attributesunimplemented!()}#[proc_macro]#[proc_macro_error]pub fn make_answer(input: TokenStream) -> TokenStream {let input = parse_macro_input!(input as ItemStruct);let attrs = process_attrs(&input.attrs);// abort right now if some errors were encountered// at the attributes processing stageabort_if_dirty();let fields = process_fields(&input.fields);// no need to think about emitted errors// #[proc_macro_error] will handle them for you//// just return a TokenStream as you normally wouldquote!(/* stuff */).into()}
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。