← 返回刚才阅读的位置

知识卡片

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

用解析特征定义输入语法

理解等级:中级

为自定义类型实现 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 处

    参考来源

    - 位置:《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#p92) - 结论依据:第 4.6.2 节与图 4.4 逐步处理 pub second: u32,说明 Ident 的限制、两个入口的流类型与重解析代价,练习 6 提出按类型依次读取。 - 原始内容: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.