← 返回刚才阅读的位置

知识卡片

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

自定义关键字驱动解析

理解等级:中级

Rust 过程宏可以在自己的语法中赋予普通单词特殊含义。用 syn::custom_keyword! 定义 bucket 和 lambda 后,syn 会为它们生成可用于前瞻和 Parse 的类型。顶层 IacInput::parse 用 peek 查看下一个 token,再委派给 Bucket 或 Lambda 消费关键字和其后的字段。交由子解析器处理的关键字即使无需保存,也要消费掉,解析游标才会前进。

遇到未知 token 时可以在前瞻位置返回 syn::Error。本章把 bucke 的诊断指向该 token,并提示支持的两个资源关键字。末尾还有一项跨声明检查,=> 要求存在 Lambda。原始示例用独立的 Option 槽位,重复的桶声明会覆盖前值,分派机制本身并未约束声明次数。

相关卡片 [[字段类型限定合法输入]]、[[用泛型复用关键字解析]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Writing an infrastructure DSL 解析原始资源语法 · 查看原书依据

      Within our macro, lambda and bucket have a special meaning. Both act like a sort of keyword for a “resource declaration,” which is followed by—required and optional—resource details. But for Rust/syn, there is no reason to treat either of these words as something special. So we can use the custom_keyword macro to tell syn that these two are keywords within our macro.

    参考来源

    - 位置:《Write Powerful Rust Macros》第09章《Writing an infrastructure DSL》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-9.xhtml#p52) - 结论依据:原书解释了自定义关键字如何给宏内单词赋予资源声明角色,顶层分派和错误位置见清单 9.5–9.6。 - 原始内容:Within our macro, lambda and bucket have a special meaning. Both act like a sort of keyword for a “resource declaration,” which is followed by—required and optional—resource details. But for Rust/syn, there is no reason to treat either of these words as something special. So we can use the custom_keyword macro to tell syn that these two are keywords within our macro.