简体   繁体   English

如何在程序宏中接受语法上无效的输入?

[英]How do I accept syntactically invalid input in a procedural macro?

I thought that procedural macros only had to have lexically-valid input, but it seems like all input must also parse as Rust code, unless I'm doing something wrong.我认为过程宏只需要具有词法上有效的输入,但似乎所有输入也必须解析为 Rust 代码,除非我做错了什么。

The RFC says: RFC 说:

By operating on tokens, code passed to procedural macros does not need to satisfy the Rust parser, only the lexer.通过对令牌进行操作,传递给过程宏的代码不需要满足 Rust 解析器,只需要满足词法分析器。

As soon as the input involves invalid Rust syntax I get parse errors.一旦输入涉及无效的 Rust 语法,我就会收到解析错误。

Consider the following procedural macro:考虑以下程序宏:

#[proc_macro_attribute]
pub fn my_macro(_: TokenStream, _: TokenStream) -> TokenStream {
    TokenStream::from(quote! {})
}

when run on:运行时:

#[my_macro]
fn test() { * } // lexically valid but syntactically invalid

I get the error:我收到错误:

error: expected expression, found `}`
  --> blah.rs:38:2
   |
33 | #[logic] fn omg () { * }
   |                        ^ expected expression

cargo-expand shows that the macro correctly deletes the function. cargo-expand显示宏正确删除了函数。 Shouldn't it thus stop any parse error?难道它不应该停止任何解析错误吗?

What am I doing wrong?我究竟做错了什么?

By reading the proc-macro RFC closely, I noticed that this is a documented behavior of attribute-like proc-macros:通过仔细阅读 proc-macro RFC,我注意到这是类似属性的 proc-macros 的记录行为:

The second argument is the tokens for the AST node the attribute is placed on.第二个参数是属性所在的 AST 节点的标记。 Note that in order to compute the tokens to pass here, the compiler must be able to parse the code the attribute is applied to.请注意,为了计算要在此处传递的标记,编译器必须能够解析应用该属性的代码。

To work around this it seems like the only choice is to use a function-like macro which does not have this limitation, which changes the syntax slightly, it's too bad but not the end of the world for me.为了解决这个问题,似乎唯一的选择是使用一个没有这个限制的类似函数的宏,它稍微改变了语法,这太糟糕了,但对我来说不是世界末日。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM