知识卡片
游标读取不消耗输入
ParseStream::cursor() 用于低层查看 token。诸如 cursor.ident() 返回读到的标识符与一个后继游标,继续读会沿后继游标前进,原 ParseStream 的消费位置保持原样。直接从自定义 Parse 返回结果时,若底层流仍有未消费 token,parse2 的完整输入检查会报 unexpected token。
书中的版本在游标读取后把剩余流再读成 proc_macro2::TokenStream,以演示如何让检查通过。这个做法若不验证尾部,可能接纳额外 token。示例还用字符串包含 pub 猜可见性,会把类似 public_name 的字段名误当成修饰符,也处理不了 pub(crate) 的分组。常规 Rust 语法优先交给类型化解析,遇到确实需要低层读取的规则再精确定义匹配、消费和报错。
相关卡片 [[用解析特征定义输入语法]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Making fields public with attribute macros 游标读取及方案取舍 · 查看原书依据
The final let _: Result<proc_macro2::TokenStream, _> = input.parse(); is icky, though. cursor is giving us immutable access to the existing stream. This is great—except that after calling your parsing method, parse2 does a check to make sure there’s nothing left unhandled inside your stream. And, in our case, we did not—could not, even—change anything, so we will get a confusing Error("unexpected token") error. So we just call parse and