知识卡片
为组合语法解析点号列表
小型领域语法可以直接从函数式过程宏的 token 中解析。对 compose!(add_one . add_one . stringify),只需把函数位置建模为 Ident,把分隔符建模为点号。语法类型 ComposeInput 持有 Punctuated<Ident, Token![.]>。在 Parse 实现中运行 parse_terminated,得到含元素和标点的序列。这里 Token![.] 指向 syn 的 Dot 类型,语法更换标点时可一起修改解析和调用样例。
这一文法接收单个名字,不能解析 module::f 或闭包等完整路径与表达式。列表解析能接受空列表或尾标点,组合操作所需的最小长度、尾标点是否符合约定,需要另行校验。
相关卡片 [[逆向生成顺序执行的组合]]、[[函数式宏替换调用]]。
结构图:
classDiagram
class ComposeInput {
+Punctuated expressions
+parse(input: ParseStream) Result$
+to_tokens(&self, tokens: &mut TokenStream)
}
class Punctuated {
+parse_terminated(input: ParseStream) Result$
+iter() Iter
}
class Parse {
<<trait>>
+parse(input: ParseStream) Result$
}
class ToTokens {
<<trait>>
+to_tokens(&self, tokens: &mut TokenStream)
}
class Ident
class Dot
ComposeInput *-- Punctuated : expressions
Punctuated *-- Ident : 列表元素
Punctuated *-- Dot : 列表标点
Parse <|.. ComposeInput : 实现
ToTokens <|.. ComposeInput : 实现
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 读取标识符并折叠调用 · 查看原书依据
The Parse input is simple enough: we expect to get function names separated by dots. That sounds like Punctuated! Identifiers will suffice for the function names (see figure 5.3). And to get the dot, we can use the Token macro, which can handle around 100 different symbols. Behind the scenes, Token!(.) will generate Dot, so we could also import that type. Or we could even mix and match these two if we are so inclined.