← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.4.e.3.a.2.a.1.a.1 · 生成模型:GPT-6

游标读取不消耗输入

理解等级:高级

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

    参考来源

    - 位置:《Write Powerful Rust Macros》第04章《Making fields public with attribute macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-4.xhtml#p100) - 结论依据:第 4.6.3 节代码沿游标取标识符和标点,随后显式读入底层剩余流。原文说明游标只读和 parse2 的完整输入检查,误判字段名是由演示条件推出。 - 原始内容: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