← 返回刚才阅读的位置

知识卡片

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

逆向生成顺序执行的组合

理解等级:中级

二元组合函数 compose_two(f, g) 返回闭包 move |x| g(f(x))。它要求前一函数的输出类型能作为后一函数的输入。对 a . b . c,取最后一个标识符 c,从右向左把 b 与 c 组合为中间片段,再把 a 加在外层,得到 compose_two(a, compose_two(b, c))。展开时构造语法片段的方向与运行时处理输入的顺序不同,调用生成的闭包仍先执行 a,再执行 b 和 c。

书中实现读取末项时使用 unwrap,空列表会 panic。单元素列表无迭代,因此 total 仍为空,块里缺少组合表达式,求值为单元值 ()。若宏只接受至少两个函数,应在输入解析时明确拒绝较短的列表。若打算支持单个函数,应原样生成该函数。

相关卡片 [[为组合语法解析点号列表]]、[[用块容纳生成的辅助函数]]。

结构图:

flowchart TD
    A["输入 a . b . c"] --> B["取末项 c"]
    B --> C["生成 compose_two(b, c)"]
    C --> D["生成 compose_two(a, 上一片段)"]
    D --> E["闭包执行 a → b → c"]
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第05章《Hiding information and creating mini-DSLs with function-like macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-5.xhtml#p86) - 结论依据:清单 5.7 的二元闭包给出执行顺序,清单 5.8 和图 5.4 给出逆序构造过程。空列表和单元素列表的表现由 pop、total 和最终输出推得。 - 原始内容:is empty, we are at our first element and should combine it with last_ident using compose_two, putting that entire TokenStream into total. This is why we popped the last element: so we would know when we need to combine the first two elements of the reversed vector. Once past this first composition, things become simpler: we keep taking the current element and putting it into a compose_two with the current total. The resulting TokenStream becomes