知识卡片
生成代码要在调用端验证
宏 crate 的编译可以验证生成器自己是合法 Rust,并能返回令牌流。quote! 能构造语法上尚未有效的令牌序列。例如生成的函数名后面多了一个单词,宏库仍可能通过 cargo check。消费端实际触发宏时,编译器才会在输出位置解析这些令牌并作语义检查。为宏保留独立调用场景来检验展开结果和诊断。
相关卡片 [[宏展开后仍要检查]]、[[在调用端查看宏展开]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 为何在应用侧验证
原书出处 · 1 处
- A “Hello, World” procedural macro 为何在应用侧验证 · 查看原书依据
This makes sense because within the library we are not using the generated code. All Rust cares about is that we declared TokenStream to be the return type of our function. And as long as we return any stream of tokens, even an invalid one, it is happy.
参考来源
- 位置:《Write Powerful Rust Macros》第03章《A “Hello, World” procedural macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-3.xhtml#p50)
- 结论依据:原书把错误函数输出放入 quote,宏库检查通过,消费端在派生处报语法错误。
- 原始内容:This makes sense because within the library we are not using the generated code. All Rust cares about is that we declared TokenStream to be the return type of our function. And as long as we return any stream of tokens, even an invalid one, it is happy.