Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top