← 返回起始笔记位置

知识卡片

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

为组合语法解析点号列表

理解等级:中级

小型领域语法可以直接从函数式过程宏的 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 处

    参考来源

    - 位置:《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#p83) - 结论依据:第 5.3 节以 ComposeInput 区别于现成的 DeriveInput,图 5.3 和清单 5.8 表明元素、标点及解析方法的选择。长度、路径限制来自该文法和生成端代码。 - 原始内容: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.