< 返回版块

苦瓜小仔 发表于 2022-01-20 02:10

地址:zjp-CN/proc-macro-workshop

此解答未参考别的解答,完全独立编写。

procedural macros workshop 是什么?

它是 dtolnay 提供的一份过程宏实战教程。你也可以把它看做带你深入了解编写过程宏的 rustlings。

建议:

  1. 按照作者介绍的顺序编写,因为这个顺序是由易到难的;
  2. 千万不要忽视 README、和代码中的所有注释;
  3. 千万不要忽视 syn 和 quote 的文档及其文档样例代码;

P.S. 其他学习建议参考我学习编写 Rust 过程宏时写的一个小案例,这个案例灵感来自于论坛的这个帖子。

最后附上 dtolnay 在教程中的一段话:

There is only one profound insight about Rust macro development, and this test case begins to touch on it: what makes someone an "expert at macros" mostly has nothing to do with how good they are "at macros".

95% of what enables people to write powerful and user-friendly macro libraries is in their mastery of everything else about Rust outside of macros, and their creativity to put together ordinary language features in interesting ways that may not occur in handwritten code.

You may occasionally come across procedural macros that you feel are really advanced or magical. If you ever feel this way, I encourage you to take a closer look and you'll discover that as far as the macro implementation itself is concerned, none of those libraries are doing anything remotely interesting. They always just parse some input in a boring way, crawl some syntax trees in a boring way to find out about the input, and paste together some output code in a boring way exactly like what you've been doing so far. In fact once you've made it this far in the workshop, it's okay to assume you basically know everything there is to know about the mechanics of writing procedural macros.

To the extent that there are any tricks to macro development, all of them revolve around what code the macros emit, not how the macros emit the code. This realization can be surprising to people who entered into macro development with a vague notion of procedural macros as a "compiler plugin" which they imagine must imply all sorts of complicated APIs for how to integrate with the rest of the compiler. That's not how it works. The only thing macros do is emit code that could have been written by hand. If you couldn't have come up with some piece of tricky code from one of those magical macros, learning more "about macros" won't change that; but learning more about every other part of Rust will. Inversely, once you come up with what code you want to generate, writing the macro to generate it is generally the easy part.

src: bitfield/tests/04-multiple-of-8bits.rs

评论区

写评论

还没有评论

1 共 0 条评论, 1 页