如何序列化 antlr3 AST
我刚刚开始使用 antlr3,并尝试序列化 .g 语法的 AST 输出。
谢谢,
莱赞
I have just started using antlr3 and am trying to serialize the AST output of a .g grammar.
Thanks,
Lezan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Vladimir 指出的,您可以使用具有内置序列化功能的自定义 AST 节点类。您还可以使用树适配器来创建所需的节点类型。
如果您只需要序列化,而不需要反序列化,您可能可以这样做:
上面将为您提供类似 LISP 的树结构。进行序列化的一种简单方法是将其与具有重写的
toString()
的自定义 AST 节点类结合使用。由于toStringTree()
使用节点的toStringTree
方法,因此它本质上会序列化您放入toString
中的任何内容。使其输出足够且有用,您就应该做好准备。As Vladimir pointed out, you can use a a custom AST node class that has serialize capabilities builtin. You could also use a tree adaptor to create the types of nodes you need.
If you only need serialization, and not de-serialization, you could probably just do:
The above will give you a LISP like tree structure. An easy way to do serialization would be to use that in combination with a custom AST node class with an overridden
toString()
. SincetoStringTree()
uses the node'stoStringTree
method, it'll essentially serialize whatever you put intoString
. Make its output sufficient and useful and you should be set.Parser 生成的 CommonTree 节点不可序列化。
我建议您序列化令牌并稍后使用辅助语法来解析(反序列化)令牌流。在《The Definitive ANTLR Reference》(The Definitive ANTLR Reference)一书中,Terence Parr 准确地给出了这种场景——虽然没有序列化,但序列化对于标记来说是微不足道的,因为它们只是文本。
我还认为您可以用自己的类替换 Tree 类:
但我还没有尝试过。
CommonTree nodes produced by Parser are not Serializable.
I'd suggest you to serialize Tokens and use a secondary grammar for parsing the (deserialized) stream of Tokens later. In the book (The Definitive ANTLR Reference), in the Quick Tour for Impatient chapter, Terence Parr gives exactly this scenario -- without serialization though, but serialization is trivial for tokens as they are just text.
My understanding also that you can replace the Tree class with your own:
But I haven't tried it.