知识卡片

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

属性形状决定解析方法

理解等级:中级

syn::Attribute 的 meta 记录属性的外层语法。在 syn 2 中,先判断外层形态,再按宏约定处理内部值。

书中形态 外层节点 取得内容的方式
#[builder_defaults] Meta::Path 用路径名匹配标记
#[rename("tops_of")] Meta::List 用 parse_args::<LitStr>() 解析唯一字符串
#[rename(tops_of)] Meta::List 解析组内标识符
#[rename = "tops_of"] Meta::NameValue 从 value 的 Expr::Lit 中匹配 Lit::Str

像 #[serde(rename = "name")] 这种写法的外层仍是列表,键值位于组内。要求指定形态时,可用 require_list 等帮助函数将不匹配作为错误处理。

相关卡片 [[字符串属性生成标识符]]、[[属性宏参数的结构化解析]]。

结构图:

classDiagram
    class Attribute {
        meta Meta
    }
    class Meta {
        <<enumeration>>
        Path
        List
        NameValue
    }
    class MetaList {
        path Path
        tokens TokenStream
        +parse_args() Result
    }
    class MetaNameValue {
        path Path
        value Expr
    }
    Attribute *-- Meta : 元数据
    Meta *-- MetaList : List 变体
    Meta *-- MetaNameValue : NameValue 变体
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Builder with attributes 理解属性形态与取值 · 查看原书依据

      In our case, the last one, a list of exactly one element, is correct. We will keep things simple by panicking when we receive the wrong attribute format. But I would be amiss if I didn’t point out that meta has a couple of useful methods for this very situation. require_list will return the nested MetaList if it is present or an Err if we received a different enum variant.

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p38) - 结论依据:图 8.1、图 8.2 和清单 8.5、8.10 分别说明列表与键值表示在 syn 2 中的 AST 入口及取值方式。 - 原始内容:In our case, the last one, a list of exactly one element, is correct. We will keep things simple by panicking when we receive the wrong attribute format. But I would be amiss if I didn’t point out that meta has a couple of useful methods for this very situation. require_list will return the nested MetaList if it is present or an Err if we received a different enum variant.