proc-macro-workshop:debug-1
审题
// This test looks for a derive macro with the right name to exist. For now the
// test doesn't require any specific code to be generated by the macro, so
// returning an empty TokenStream should be sufficient.
//
// Before moving on, have your derive macro parse the macro input as a
// syn::DeriveInput syntax tree.
//
//
// Resources:
//
// - The DeriveInput syntax tree which represents input of a derive macro:
// https://docs.rs/syn/1.0/syn/struct.DeriveInput.html
//
// - An example of a derive macro implemented using Syn:
// https://github.com/dtolnay/syn/tree/master/examples/heapsize
use derive_debug::CustomDebug;
#[derive(CustomDebug)]
pub struct Field {
name: &'static str,
bitmask: u16,
}
fn main() {}
从这一关的测试用例不难发现,解题方式不过也是一个占位,相当于是热身。
题解
详细可以参看builder-1,这里直接粘贴代码。
#[proc_macro_derive(CustomDebug, attributes(debug))]
pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
match solution1(&ast) {
syn::Result::Ok(token_stream) => {
return proc_macro::TokenStream::from(token_stream);
}
syn::Result::Err(e) => {
return e.into_compile_error().into();
}
}
}
当然,代码里面直接Result::Ok(proc-macro2:: TokenStream::new())
即可,因为当前的确不需要做任何的事情。
整体
#[proc_macro_derive(CustomDebug, attributes(debug))]
pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
match solution1(&ast) {
syn::Result::Ok(token_stream) => {
return proc_macro::TokenStream::from(token_stream);
}
syn::Result::Err(e) => {
return e.into_compile_error().into();
}
}
}
要用以前的分步习惯,我们之后还是把常用的方法抽取到common.rs
,其他每个问题的回答抽取到对应的solutionx.rs
中
本作品采用《CC 协议》,转载必须注明作者和本文链接