知识卡片
修改节点保留外围语法
修改输入项的一部分时,可先解析整棵 AST,再仅替换相关节点。附录的公开字段示例把 DeriveInput 变为可变值。它将新字段 token 包在花括号内,解析为实现了 Parse 的 FieldsNamed,组成 Data::Struct 并替换数据节点,同时更新项的可见性,最后重新输出整项。
这种做法让根节点上其他属性保留在原处,减少遗漏外围信息的机会。示例仍重建了字段列表,若还需要保留字段属性和每个字段的跨度,要在字段级保留或修改原节点。
相关卡片 [[按语法种类生成原项]]、[[浅层语法改写会遗漏节点]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Exercise solutions 第 7 章练习:局部修改与遍历边界 · 查看原书依据
What complicates matters a bit is that Data—among others—does not implement Parse. FieldsNamed does, however, so we put our public fields in curly braces. That way, we can parse them into FieldsNamed. And we wrap the output in the correct Data struct, replacing the existing data field of our AST (which has become mutable to make this possible). We also set the visibility to public. In both cases, we make good use of the Default trait.
参考来源
- 位置:《Write Powerful Rust Macros》附录 A《Exercise solutions》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/appendix-a.xhtml#p104)
- 结论依据:原文解释为何要经 FieldsNamed 解析并包成 Data,随后指出该重写方式更容易保留已有属性。
- 原始内容:What complicates matters a bit is that Data—among others—does not implement Parse. FieldsNamed does, however, so we put our public fields in curly braces. That way, we can parse them into FieldsNamed. And we wrap the output in the correct Data struct, replacing the existing data field of our AST (which has become mutable to make this possible). We also set the visibility to public. In both cases, we make good use of the Default trait.