知识卡片

结构图卡 · 6074.d.1.a.3.c.4.e.1.a.1.a · 生成模型:GPT-6

过程宏入口与实现分离

理解等级:中级

让过程宏 crate 只接收和归还编译器的 proc_macro::TokenStream,在入口把输入转为 proc_macro2::TokenStream 再委托给普通库。普通库用 syn::parse2 读取语法,用 quote! 生成输出。出口再把结果转回编译器需要的类型。这样可以直接调用生成函数做普通单元测试,同时让独立的使用方 crate 验证展开代码。工作区能统一运行三处的检查,但是否拆成三个 crate 取决于隔离收益。

结构图:

flowchart LR
    A[使用方 crate] --> B[过程宏入口 crate]
    B -->|传入 proc_macro2 令牌流| C[普通生成库]
    C -->|归还生成的令牌流| B
    B -->|交给编译器展开| A
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Testing a builder macro 工作区、生成库与宏入口 · 查看原书依据

      The macro definition is very similar to the one we had before, except that it is now in a separate package. We have defined a derive macro called Builder that accepts a normal TokenStream as a parameter and returns another. Because our builder-code is only using the proc_macro2, we are forced into a “translation” when we pass this data to builder-code.

    参考来源

    - 位置:《Write Powerful Rust Macros》第06章《Testing a builder macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-6.xhtml#p33) - 结论依据:书中清单 6.1–6.4 将调用项目、宏入口和生成逻辑放在同一工作区,清单 6.3 在入口两次用 Into 转换 token 流。 - 原始内容:The macro definition is very similar to the one we had before, except that it is now in a separate package. We have defined a derive macro called Builder that accepts a normal TokenStream as a parameter and returns another. Because our builder-code is only using the proc_macro2, we are forced into a “translation” when we pass this data to builder-code.