知识卡片
自定义关键字驱动解析
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.