如何序列化 antlr3 AST

发布于 2024-08-12 04:50:36 字数 58 浏览 3 评论 0原文

我刚刚开始使用 antlr3,并尝试序列化 .g 语法的 AST 输出。
谢谢,
莱赞

I have just started using antlr3 and am trying to serialize the AST output of a .g grammar.
Thanks,
Lezan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜点 2024-08-19 04:50:36

正如 Vladimir 指出的,您可以使用具有内置序列化功能的自定义 AST 节点类。您还可以使用树适配器来创建所需的节点类型。

如果您只需要序列化,而不需要反序列化,您可能可以这样做:

ast.toStringTree()

上面将为您提供类似 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:

ast.toStringTree()

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(). Since toStringTree() uses the node's toStringTree method, it'll essentially serialize whatever you put in toString. Make its output sufficient and useful and you should be set.

惟欲睡 2024-08-19 04:50:36

Parser 生成的 CommonTree 节点不可序列化。

我建议您序列化令牌并稍后使用辅助语法来解析(反序列化)令牌流。在《The Definitive ANTLR Reference》(The Definitive ANTLR Reference)一书中,Terence Parr 准确地给出了这种场景——虽然没有序列化,但序列化对于标记来说是微不足道的,因为它们只是文本。

我还认为您可以用自己的类替换 Tree 类:

options {
  ASTLabelType = MyOwnTreeClass;
}

但我还没有尝试过。

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:

options {
  ASTLabelType = MyOwnTreeClass;
}

But I haven't tried it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文