知识卡片
用解析特征定义输入语法
为自定义类型实现 syn::parse::Parse,可用 fn parse(input: ParseStream<'_>) -> syn::Result<Self> 声明怎样从输入缓冲区消费语法并得到一个值。书中先读 Visibility,显式 pub 会被读过,无修饰符则得到 Inherited。接着把余下内容当成按冒号分隔的标识符,取第一项作字段名、最后一项作类型。这个演示依赖上游已产出一个具名字段,还假定它没有附加属性,类型是单一标识符。完整类型如 Vec<String> 需要使用 syn::Type。对于语法是单一字段的情况,直接依次读 Visibility、Ident、冒号与 Type 更能表达各部分的角色。
syn::parse 接受 proc_macro::TokenStream,syn::parse2 接受 proc_macro2::TokenStream,目标类型需实现 Parse。从 syn 已解析的 Field 重新生成 token 再解析,仅用于展示替代写法。处理既有 Rust 字段可直接使用 AST,确有自定义语法时适合从宏的输入起点按该文法建立模型。
相关卡片 [[用字段模型委托输出]]、[[游标读取不消耗输入]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Making fields public with attribute macros 让字段模型负责解析 · 查看原书依据
If visibility was still part of our stream at this stage, Rust would complain with Error("expected identifier"), because it expected a list of identifiers and got a Visibility type. But even though we avoid that error, this is still not a production-ready macro.