proc-macro-workshop:seq-1
审题
// This test looks for a function-like 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 to the next test, you'll want some code in your
// implementation to handle parsing the first few tokens of input. The macro
// should expect the input to contain a syn::Ident, Token![in], syn::LitInt,
// Token![..], syn::LitInt.
//
// It is also possible to implement this project without using Syn if you'd
// like, though you will end up writing more code, more tedious code, and more
// explicit error handling than when using Syn as a parsing library.
//
//
// Resources:
//
// - Parsing in Syn:
// https://docs.rs/syn/1.0/syn/parse/index.html
//
// - An example of a function-like procedural macro implemented using Syn:
// https://github.com/dtolnay/syn/tree/master/examples/lazy-static
use seq::seq;
seq!(N in 0..8 {
// nothing
});
fn main() {}
还是熟悉的味道,之前我们使用的是syn::DeriveInput
,但是实际上我们可以自定义解析结构。
这也是seq
中我们需要做的:自定义语法解析。
虽然这一关没有更多的要求,但是我们还是简单的抽取一下我们将要解析的结构。
结构
pub(crate) struct SeqParser {
pub(crate) variable_ident: syn::Ident,
pub(crate) begin: usize,
pub(crate) end: usize,
pub(crate) body: proc_macro2::TokenStream,
}
对照一下测试用例
seq!(N in 0..8 {
// nothing
});
我们需要解析的几个部分如下
variable_ident
:N
in
:in
begin
: 0..
:..
end
:8{}
:{}
tokens
:nothing
关键的数据正如上述结构,后续的使用我们再一一调整。
题解
#[proc_macro]
pub fn seq(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
proc_macro2::TokenStream::new().into()
}
第一关还是熟悉的练手,直接返回结构即可。
具体的解析会在第二关进行。
本作品采用《CC 协议》,转载必须注明作者和本文链接